I have a byte array which I need to traverse and based on the byte value do something. Below is my code for this.
for (byte b:byteArray)
{
if(b>=(byte)0x00 && b<=(byte)0x1F)
{
//do something
}
else if(b>=(byte)0x20 && b <=(byte)0xFE)
{
//do something
}
else if(b ==(byte)0xFF)
{
//do something
}
}
My problem the byte comparison is not happening as per my expectation.
Assume the values in my byte array is {31, -117, 8, 0 , -1}
, the code I have is not able to detect all negative byte values in their respective range. For ex. -117 should be between 0x20
and 0xFE
, but it is not going to any of the range.
I have followed this answer to compare bytes. I cannot figure out what is wrong in the code.
Thanks in advance!
Your relations only make sense on unsigned bytes - which do not exist in Java.
Try this:
for (byte b:byteArray)
{
int ib = b & 0xFF; // This scales up to integer so you have values 0-255
if(ib >=0x00 && ib<=0x1F)
{
//do something
}
else if(ib>=0x20 && ib <=0xFE)
{
//do something
}
else if(ib == 0xFF)
{
//do something
}
else
{
// log a bug! This should never happen!
}
}
In your solution -117 is 0x8B , which is in fact less than 0x20 (Dec 32), so it does not meet the 2nd path criteria b >= 0x20
. In fact this creates unreachable code because no value is > 32 and <= -2.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments