這可能是一個更有經驗的程序員的基本問題。我是一個小白,不能工作這一個。我試圖解開一個二進制文件,並且doco對於如何存儲浮動內容不太清楚。我找到了一個這樣做的例程,但只有當我傳遞一個字節的整數數組時纔會起作用。正確答案是-1865.0。我需要能夠傳遞字節數組並獲得正確的答案。我如何需要更改代碼以使float4byte返回-1865.0。提前致謝。將字節[4]轉換爲浮點數 - 整型[4]數組可以工作,但字節[4]不會
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
public class HelloWorld {
public static void main(String[] args) {
byte[] bytes = {(byte) 0xC3,(byte) 0X74,(byte) 0X90,(byte) 0X00 };
int[] ints = {(int) 0xC3,(int) 0X74,(int) 0X90,(int) 0X00 };
// This give the wrong answer
float f = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).getFloat();
System.out.println("VAL ByteBuffer BI: " + f);
// This give the wrong answer
f = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
System.out.println("VAL ByteBuffer LI: " + f);
//This gives the RIGHT answer
f = float4int (ints[0], ints[1], ints[2], ints[3]);
System.out.println("VAL Integer : " + f);
// This gives the wrong answer
f = float4byte (bytes[0], bytes[1], bytes[2], bytes[3]);
System.out.println("VAL Bytes : " + f);
}
private static float float4int(int a, int b, int c, int d)
{
int sgn, mant, exp;
System.out.println ("IN Int: "+String.format("%02X ", a)+
String.format("%02X ", b)+String.format("%02X ", c)+String.format("%02X ", d));
mant = b << 16 | c << 8 | d;
if (mant == 0) return 0.0f;
sgn = -(((a & 128) >> 6) - 1);
exp = (a & 127) - 64;
return (float) (sgn * Math.pow(16.0, exp - 6) * mant);
}
private static float float4byte(byte a, byte b, byte c, byte d)
{
int sgn, mant, exp;
System.out.println ("IN Byte : "+String.format("%02X ", a)+
String.format("%02X ", b)+String.format("%02X ", c)+String.format("%02X ", d));
mant = b << 16 | c << 8 | d;
if (mant == 0) return 0.0f;
sgn = -(((a & 128) >> 6) - 1);
exp = (a & 127) - 64;
return (float) (sgn * Math.pow(16.0, exp - 6) * mant);
}
}
此解決方案完美運作。問題解決了。謝謝。我將需要扭轉過程並以相同的方式重新打包浮動。不知道我知道如何。任何提示如何做到這一點也不勝感激。 –
@Andrew L:爲反向函數'byte4float'添加了一個示例實現。請參閱編輯。 – halfbit
謝謝@halfbit。我發現的是,我正在使用舊的IBM 370大型機float。請參閱[IBM_Floating_Point_Architecture](https://en.wikipedia.org/wiki/IBM_Floating_Point_Architecture#IEEE_754_on_IBM_mainframes)。這個解決方案並不完善,但還有一些工作要做。 –