2

I am trying to take bytes and display them as an integer in android. I am using the bluetooth chat as a template, and am sending data from a bluetooth device, which is working fine and displaying fine. Now, instead of displaying the char set of the byte that is being sent, I want to display the integer value. This is the code from the Handle in the Bluetooth Chat developer code.

byte[] writeBuf = (byte[]) msg.obj;

// construct a string from the buffer
String writeMessage = new String(writeBuf);

mConversationArrayAdapter.add("Me:  " + writeMessage);

I have tried making the byte array an integer array, which works however, I cannot get an integer array into a string... Can anyone help?

1
  • 1
    What do you mean by "the integer value"? The ASCII code? The numeric conversion, "0" -> 0, "1" -> 1, etc? Commented Dec 14, 2011 at 8:53

1 Answer 1

3

You can use ByteBuffer assuming you know the byte order (big vs little endian)

byte[] writeBuf = (byte[]) msg.obj;

// construct a string from the buffer
String writeMessage = String.valueOf(ByteBuffer.wrap(writeBuf).getInt()));

If you want little endian you can use .order(ByteOrder.LITTLE_ENDIAN)

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

2 Comments

+1 Very cool. I haven't used ByteBuffer before. Looks really useful for avoiding the pain and code bloat of dealing with a byte[]. P.S. Pick an avatar sometime!
Similarly you can get (byte), getLong, getDouble, getFloat, getShort etc and a combination of these (you can have a byte[] with comination of data types) You can also build a byte[] from primitives as well.

Your Answer

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