0

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.

1
  • A Java String is composed of characters from a character set. When you supply a byte array to the String constructor those bytes are expected to be a valid encoding of a sequence of such characters. A byte array of arbitrary byte values is not likely to to work here. Commented Oct 11, 2015 at 16:47

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

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.