Hexadecimal and long in Java

Summary

When performing bitwise operations with hexadecimal literals and long integers in Java, developers might encounter unexpected results if the literal's type is not explicitly specified. A common pitfall involves using a hexadecimal number like 0x00000000FFFFFFFF, which Java interprets as an int (0xFFFFFFFF) by default. This default interpretation, when used in a bitwise AND with a long, can lead to sign extension and incorrect masking, failing to zero out the high 32 bits as intended. To ensure the literal is treated as a long and performs the desired masking correctly, append an 'L' to the hexadecimal number, such as 0x00000000FFFFFFFFL. Always verify literal types to avoid subtle bugs in bit manipulation.

Today I encountered a hexadecimal operation problem when I was implementing a bit reverse function for integer type. Basically in the implementation, there is an operation which is to do the bit operation & between one long integer and a hexadecimal number 0x00000000FFFFFFFFF. I was expecting that the high 32 bits of the long integer will be zeroed. But unfortunately I didn't get the expected result.

The basic implementation is:

long num=0x00F0_0000;
num = (num>>16) | (num<<16);    //Here the result will be 0x000000F0000000F0
num = num & 0x00000000_FFFFFFFF;
System.out.println("Output : "+num);
//Output : 1030792151280

Actually I was expecting the result to be 240. After carefully reading the Oracle documentation, I figured out the issue, this is because I mistakenly think that 0x00000000_FFFFFFFF is a long integer, but in fact it is not, it's an integer. If we want it to be a long integer, we have to add a trailing L at the end of the number, i.e, 0x00000000_FFFFFFFFL. Otherwise, it will be treated as an integer which equals to 0xFFFFFFFF, when this number is bitwise and with the num 0x000000F0000000F0, the end result will still be 0x000000F0000000F0.

So the final implementation should be :

long num=0x00F0_0000;
num = (num>>16) | (num<<16);    //Here the result will be 0x000000F0000000F0
num = num & 0x00000000_FFFFFFFFL;
System.out.println("Output : "+num);
//Output : 240

Hope that you will be extremely careful when you deal with long integer and at the same time need to deal with bitwise operation with hexadecimal number. Don't make the same mistake as mine. One last word, documentation is your best friend when you are in a whirlpool.

JAVA HEXADECIMAL LONG BITWISE OPERATION

  RELATED

  COMMENTS

0

No comment for this article.