user2665581
user2665581

Reputation: 75

Converting bytes to string with signed bytes

Is there a way to retain a signed byte when converting it to a string? Or alternatively make them be seen as unsigned when converting to a string?

Here is my code for example:

byte[] encodedBytes = new byte[RX_Index];
System.arraycopy(RX_Buffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes);

RX_Buffer will contain 0xBF which is -65 signed decimal. After intializing data that 0xBF byte is changed to 0xFFFD after converting to a string for some reason. I'm assuming the problem is the conversion from bytes to string with a negative number. If that can't be the case let me know. Otherwise how do I fix this problem?

Upvotes: 2

Views: 1378

Answers (2)

slartidan
slartidan

Reputation: 21596

Your android BlootoothSocket (method read(byte[])) will give you a byte array with binary data.

Do not convert that data to a String.

If you want the binary data to be interpreted as ints use this code:

int myFirstValue = encodedBytes[0];

Upvotes: 1

McDowell
McDowell

Reputation: 108939

A byte is an 8bit signed type. A char is a 16bit unsigned type.

That String constructor treats the given bytes as character data encoded in the default character encoding - on Android that is UTF-8. It will transcode those bytes to UTF-16. Anything that doesn't match a valid value or sequence in the original encoding is replaced by the replacement string.

So unlike in some languages Java Strings are not binary safe. Consider Base64 encoding the values if you need to store the data as a string.

Upvotes: 2

Related Questions