Monday 15 February 2010

java - ByteBuffer switch endianness -



java - ByteBuffer switch endianness -

i trying switch endianess of bytebuffer, there no effects it. doing wrong? maybe debug main function incorrect?

@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){ (; addcount > 0; addcount--) { buffer.put((byte)0x00); } } buffer.flip(); buffer.order( byteorder.big_endian); homecoming 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(); (byte b : bytes) { out += integer.tobinarystring(b & 255 | 256).substring(1) + " "; } system.out.println(out); }

main function prints binary string : 01111101 00000000 00000000 00000000 must prints: 00000000 10111110 00000000 00000000

you need alter endianness before putting values buffer. move line right after allocating buffer size , should fine.

// debug bytebuffer buffer = bytebuffer.allocate(octets); buffer.order( byteorder.big_endian); for(byte b: intval.tobytearray()){ buffer.put(b); }

...

in addition, endianness impact order of bytes of larger numeric values, not bytes explained here

java endianness

No comments:

Post a Comment