tvalent2
tvalent2

Reputation: 5009

How to handle negative int with Java ByteBuffer

I have an Android app that uses ByteBuffer to send an array of ints (converted to a string) to my server, which is written in Ruby. The server takes the string and unpacks it. My code to build the ByteBuffer looks like this:

ByteBuffer bytes = ByteBuffer.allocate(16);
bytes.order(ByteOrder.LITTLE_ENDIAN);

bytes.putInt(int1);
bytes.putInt(int2);
bytes.putInt(int3);
bytes.putInt(int4);

String byteString = new String(bytes.array());

This works great when the ints are all positive values. When it has a negative int, things go awry. For example, in iOS when I submit an array of ints like [1,1,-1,0], the byte string on the server is:

"\x01\x00\x00\x00\x01\x00\x00\x00\xFF\xFF\xFF\xFF\x00\x00\x00\x00"

That gets correctly unpacked to [1,1,-1,0].

In Android, however, when I try to submit the same array of [1,1,-1,0], my string is:

"\x01\x00\x00\x00\x01\x00\x00\x00\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\xEF\xBF\xBD\x00\x00\x00\x00"

Which gets unpacked to [1, 1, -272777233, -1074807361].

If I convert the negative int to an unsigned int:

byte intByte = (byte) -1;
int unsignedInt = intByte & 0xff;

I get the following:

"\x01\x00\x00\x00\x01\x00\x00\x00\xEF\xBF\xBD\x00\x00\x00\x00\x00\x00\x00"

Which gets unpacked to [1, 1, 12435439, 0]. I'm hoping someone can help me figure out how to properly handle this so I can send negative values properly.

Upvotes: 0

Views: 1144

Answers (1)

fge
fge

Reputation: 121810

Your problem is here:

String byteString = new String(bytes.array());

Why do you do that? You want to send a stream of bytes, so why convert it to a stream of chars?

If you want to send bytes, send bytes. Use an OutputStream, not a Writer; use an InputStream, not a Reader. The fact that integers are "negative" or "positive" does not matter.

Upvotes: 4

Related Questions