这可能是一个更有经验的程序员的基本问题。我是一个小白,不能工作这一个。我试图解开一个二进制文件,并且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)。这个解决方案并不完善,但还有一些工作要做。 –