2

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?

7
  • Yes, you can copy it as bits to integer and then it will be positive number. Commented Mar 8, 2014 at 19:30
  • @LeosLiterak But if I then convert those integers to strings won't they become ASCII characters? For example 0x04 will become 0x34 which I don't want to happen Commented Mar 8, 2014 at 19:33
  • 1
    Is your data a binary stream, or is it text? You should not try to store binary data in a String, and you should not try to store text in a byte[]. Commented Mar 8, 2014 at 19:35
  • 1
    @slartidan This is for android and the bytes are being received from an input stream via a bluetooth connection. As far as I know there is no other way to read the input stream other than bytes so storing text in bytes is not a choice. I have to receive binary data and text data--I don't have a choice Commented Mar 8, 2014 at 19:42
  • InputStream returns ints, not bytes. Commented Mar 8, 2014 at 19:48

2 Answers 2

2

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.

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

Comments

1

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];

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.