从十进制值到字节数组的转换公式不起作用

时间:2012-10-04 16:05:28

标签: java byte bytebuffer short

我在二进制文件的规范中有一个公式。规范详细说明了标题中各种字节的含义 特别是,一个公式说明了大约2个字节:

Byte 1  -->  7  6  5  4  3  2  1  0  
Byte 2  -->  7  6  5  4  3  2  1  0 

R  Roll 
 If 'R' = 0, Roll Angle not available 
 If 'R' = 1, Roll Angle = [((Byte 84 & 0x7F)<<8) | (Byte 85) – 900] / 10 

我需要取一个4.3之类的值并将其转换为两个字节,这样就可以使用上面的公式将其转换回4.3。令我困惑的部分是减去900。

这是我到目前为止所做的:

private byte[] getRollBytes(BigDecimal[] positionData) {

    BigDecimal roll = positionData[4];
    roll = roll.multiply(BigDecimal.TEN);
    roll = roll.add(new BigDecimal(900));
    short shortval = roll.shortValue();

    byte[] rollBytes = new byte[2];

    ByteBuffer headingbuf = ByteBuffer.wrap(rollBytes);
    headingbuf.order(ByteOrder.BIG_ENDIAN);
    headingbuf.putShort(shortval);

    //set the leftmost bit of the two bytes to 'on', meaning data is available
    rollBytes[0] = (byte) (rollBytes[0] | (0x80));

    //testing the result with my formula doesn't give me the right answer:
    float testFloat = (float) (((((rollBytes[0] & 0x7F) <<8) | rollBytes[1]) - 900) /10);           

    return rollBytes;
}

我认为在短和字节之间的转换中有些东西会丢失......

1 个答案:

答案 0 :(得分:0)

一个问题是你要投射到short。这可能不正确,因为像4.3这样的值不是整数。您可能想要转换回BigDecimal:

BigDecimal testVal = ((rollBytes[0] & 0x7F) <<8) | rollBytes[1]) - 900;
testVal = val.divide(BigDecimal.valueOf(10));

另一个问题是,您似乎在计算shortVal时再次添加900次,并再次使用rollBytes[1] = (byte) (rollBytes[1] + 900);

相关问题