Reputation: 5009
I'm trying to duplicate a byte String that I produce in Objective-C (on iOS) in Java but am having trouble. Here's the string I want to produce:
"\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
I get that string from an array of 4 integers - [1,1,0,0]
- where each integer has 4 bytes. After looking at a bunch of questions on here, I've attempted constructing that string in Java using ByteBuffer
as follows:
ByteBuffer bytes = ByteBuffer.allocate(16);
bytes.putInt(1);
bytes.putInt(1);
bytes.putInt(0);
bytes.putInt(0);
String byteString = new String(bytes.array());
However that gives me:
"\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00"
When I unpack that, the array of ints I get is [16777216, 16777216, 0, 0]
. Obviously I'm doing something wrong, and I'm hoping someone can point me in the right direction.
Upvotes: 1
Views: 379
Reputation: 14590
iOS is little-endian, so the least significant byte of a 4-byte integer comes first.
Java ByteBuffer
defaults to big-endian, so the opposite applies.
The initial order of a byte buffer is always BIG_ENDIAN
You can change this with
bytes.order(ByteOrder.LITTLE_ENDIAN);
Upvotes: 5
Reputation: 12335
What you want is:
ByteBuffer bytes = ByteBuffer.allocate(16);
bytes.putInt(16777216);
bytes.putInt(16777216);
bytes.putInt(0);
bytes.putInt(0);
String byteString = new String(bytes.array());
The endianness of the platforms are different, so when you put 4 bytes in, the bytes are reversed.
Upvotes: 0