Today's Question:  What weekend projects have you created?        GIVE A SHOUT

Technical Article => Programming =>  Java

Hexadecimal and long in Java

  sonic0002      2014-06-18 23:44:32      3,339    0

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.



Share on Facebook  Share on Twitter  Share on Google+  Share on Weibo  Share on Reddit  Share on Digg  Share on Tumblr    Delicious



No comment for this article.


Why would we need an increase or decrease button when entering handphone number?

By sonic0002