将 N 字节转换为由 Q 编号定义的浮点数
Convert a N-Bytes to a Float defined by the Q-Number
有没有一种简单的方法可以将 N 字节的字节数组转换为由 Q-Number 定义的浮点数。
In 2's Compliance(之前忘了提这个)
示例:0xFFF0 -> 使用 s3.12 Q-Number 的浮点数
Peter Lawrey 的以下建议:
private static void test(short x) {
float y = (float)(x & 0x7FFF) / (1 << 12);
if ((x & 0x8000) != 0)
y = -y;
System.out.printf("%04x: %g%n", x, y);
}
测试
test((short)0xFFF0);
test((short)0xFFFF);
test((short)0x0000);
test((short)0x0001);
test((short)0x1000);
test((short)0x9000);
test((short)0x7FFF);
输出
fff0: -7.99609
ffff: -7.99976
0000: 0.00000
0001: 0.000244141
1000: 1.00000
9000: -1.00000
7fff: 7.99976
您可以使用
byte[] bytes = ....
ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.????); // check your byte order
while(bb.remaining() > 1) {
short s = bb.getShort();
boolean signed = s < 0;
int value = s & 0x7FFF;
double d = s / 4096.0;
if (signed)
d = -d;
System.out.println(d);
}
有没有一种简单的方法可以将 N 字节的字节数组转换为由 Q-Number 定义的浮点数。
In 2's Compliance(之前忘了提这个)
示例:0xFFF0 -> 使用 s3.12 Q-Number 的浮点数
Peter Lawrey 的以下建议:
private static void test(short x) {
float y = (float)(x & 0x7FFF) / (1 << 12);
if ((x & 0x8000) != 0)
y = -y;
System.out.printf("%04x: %g%n", x, y);
}
测试
test((short)0xFFF0);
test((short)0xFFFF);
test((short)0x0000);
test((short)0x0001);
test((short)0x1000);
test((short)0x9000);
test((short)0x7FFF);
输出
fff0: -7.99609
ffff: -7.99976
0000: 0.00000
0001: 0.000244141
1000: 1.00000
9000: -1.00000
7fff: 7.99976
您可以使用
byte[] bytes = ....
ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.????); // check your byte order
while(bb.remaining() > 1) {
short s = bb.getShort();
boolean signed = s < 0;
int value = s & 0x7FFF;
double d = s / 4096.0;
if (signed)
d = -d;
System.out.println(d);
}