0

I am receiving data from a hardware device. I receive it as an array of bytes. I want to build and store a String that can show me the data of the array of bytes. This is what I have:

byte[] buffer = new byte[BUFFER_SIZE];
bytes = mmInStream.read(buffer);
String[] str = new String[bytes];
StringBuffer readMessage = new StringBuffer();

for(int i=0; i<bytes; ++i){
  str[i] = Integer.toHexString(buffer[i]);
   while (str[i].length() < 8){  //standarize size 
     str[i] = '0' + str[i];    
   }
  readMessage.append(str[i]);
}

The main problem that I have is that I am receiving unexpected bytes when I transform the bytes to String. I am receiving pure bytes so I am expecting the values to range from 0x00 to 0xFF. However, some of the bytes are transformed to bytes like 0xFFFFFF09. Why is this happening??

2
  • Not related to your problem, but what happens if mmInStream.read(buffer) returns -1? Commented Nov 30, 2011 at 9:33
  • How about [new String(buffer, 0, bytes) constructor](docs.oracle.com/javase/6//docs/api/java/lang/…, int, int))? Commented Nov 30, 2011 at 9:38

3 Answers 3

2

You should convert byte to int this way:

int byteAsInt = ((int)buffer[i]) & 0x000000FF;
str[i] = Integer.toHexString(byteAsInt);
Sign up to request clarification or add additional context in comments.

2 Comments

FWIW, the leading zeros on the literal are unnecessary.
Yes, I'm aware of that. Just wanted to make this example to be more clear.
1

byte is a signed data type, so 0xFF is -1. When converting to a larger integral type it will still be -1, i.e. 0xFFFF or 0xFFFFFFFF for 16 and 32 bit integer values.

Edit:

If you want to get the unsigned value, do a bitwise AND (&) with 0xFF when assigning to a larger variable.

2 Comments

Is there a way to ignore the sign and get the byte representation as is??
If you want to get the unsigned value, do a bitwise AND (&) with 0xFF when assigning to a larger variable.
0

Without running your code I suppose that your problem is in your inner loop.

while (str[i].length() < 8){ //standarize size str[i] = '0' + str[i];
}

What would you like to achieve? Print 0xFF instead of FF? In this case just modify one line as following:

str[i] = "0x" + Integer.toHexString(buffer[i]);

and remove the inner loop.

1 Comment

The problem is that sometimes I get the byte representation to be 8 characters long as "FFFFFF68" for those that are not the same size I just want them all to have the same size.

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.