Exception
Exception

Reputation: 2323

Compare a byte and hexadecimal

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!

Upvotes: 2

Views: 6337

Answers (2)

Fildor
Fildor

Reputation: 16084

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.

Upvotes: 5

Arjit
Arjit

Reputation: 3456

Bytes in Java are signed by default. A workaround to have unsigned bytes is something similar to having : int num = (int) bite & 0xFF

How it works, Let's suppose byte b = -128;, this is represented as 1000 0000

int num = (int)b; num is now -128 and binary representation is like this:

1111 1111 1111 1111 1111 1111 1000 0000

Lets compare num & 0xFF in binary?

1111 1111 1111 1111 1111 1111 1000 0000
&
0000 0000 0000 0000 0000 0000 1111 1111

The result is 0000 0000 0000 0000 0000 0000 1000 0000, which is 128, meaning your signed value is converted to unsigned value.

Upvotes: 3

Related Questions