Barracuda
Barracuda

Reputation: 343

Comparison of byte value and hexadecimal

I ran into a problem when comparing the value of a byte. Theoretically, the following code snippet should return true, yet it returns false.

public static void main(String [] args) {
    byte a = 3;
    if (MpegUtil.isSlice(a) == true) {
        System.out.print("Yes");
    }
    else System.out.print("No");
}

public static boolean isSlice(byte ID) {
    if (ID >= 1 && ID <= (byte) 0xaf) return true;
    else return false;
}

What the function isSlice does is: receive a byte and if it is between 1 and af (hex), it will return true, if it doesn't the returned value is False. Yet somehow it fails my test by answering false to 3.

Does anyone has an idea of why this function doesn't work?

EDIT: Thank-you for the suggestion of removing the 'byte' cast, it does indeed allow the code to function, however once the compared value is superior or equal to '0x80' the result change back to being a wrong 'false'. I know this is caused by the fact that Java considers the byte to be signed (now i'm really looking forward to Java 8), but would there be any "cleaner" version than changing the condition to:

if (ID != 0 && ID >= (byte) 0xaf && ID <= (byte) 0x7f) return true

Since this condition doesn't seem at first glance logical, is there any more obvious way to fix this?

Upvotes: 2

Views: 3790

Answers (2)

Gene
Gene

Reputation: 46960

Bytes are signed in Java. Coercing 0xaf to byte produces a negative number. The Java way is to do int comparisons. Just remove the byte cast and all should start working.

Similarly if you need to compare 32-bit unsigned quantities, you are more-or-less forced to use long comparisons.

Lack of unsigned types is one of Java's more annoying (un)features.

Upvotes: 2

Christian Tapia
Christian Tapia

Reputation: 34146

It doesn't work because (byte) 0xAF is not what you think. Try printing the following, so you get the idea:

    System.out.println(0xaf); // 175
    System.out.println((byte) 0xaf); // -81

Why is (byte) 0xAF negative?

Print this:

System.out.println(Byte.MAX_VALUE); // 127

The range of a byte is [-128, 127] (256 numbers), so if you cast 175 to byte, you will get:

175 - 256 = -81

You can also try this:

System.out.println((byte) 128); // -128
System.out.println((byte) -129); // 127
System.out.println((byte) 256); // 0

Upvotes: 5

Related Questions