1

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.

1
  • Using a String to hold bytes is not advisable. When you pass a byte array to new String, you are using the platform's default charset to decode those bytes into characters, and any byte sequences which are invalid for that charset will be decoded into the String as "?" or "�". These particular bytes don't have that problem, but any bytes above 0x7f probably will. Commented Oct 11, 2015 at 2:01

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, that did it. Thanks!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.