java ByteBuffer开关端性
我试图通过tebuffer来切换的持久性,但没有效果。我做错了什么? 可能我的调试主功能不正确
@Override
public byte[] toBytes(BigDecimal type) {
int octets = getOctetsNumber();
BigInteger intVal = type.unscaledValue();
byte[] temp = intVal.toByteArray();
int addCount = octets - temp.length;
// DEBUG
ByteBuffer buffer = ByteBuffer.allocate(octets);
for(byte b: intVal.toByteArray()){
buffer.put(b);
}
if (addCount > 0){
for (; addCount > 0; addCount--) {
buffer.put((byte)0x00);
}
}
buffer.flip();
buffer.order( ByteOrder.BIG_ENDIAN);
return buffer.array();
}
public static void main(String[] arg) {
IntegerDatatype intVal = new IntegerDatatype(17);
BigDecimal bd = new BigDecimal(32000);
byte[] bytes = intVal.toBytes(bd);
String out = new String();
for (byte b : bytes) {
out += Integer.toBinaryString(b & 255 | 256).substring(1) + " ";
}
System.out.println(out);
}
主函数打印此二进制字符串:01111000000000 00000000 但必须打印:00000000 10111110 00000000 00000000
# 1 楼答案
在将值放入缓冲区之前,需要更改endianness。 只需在分配缓冲区大小后向右移动该行,就可以了
此外,endianness只影响较大数值的字节顺序,而不影响所解释的字节here
# 2 楼答案
应在创建缓冲区后立即设置,请参见
http://www.javamex.com/tutorials/io/nio_byte_order.shtml