You can use technology for years and yet still only be touching only the tip of the iceberg.
Recently I needed to extract the least significant bytes out of a long number in Java. In some cases I needed the 8 bits, in others, it was 16 or 32 bits.
That task can be accomplished simply by using a mask of any of those given sizes and apply it with a bitwise AND operation and everything would be thrown away.
if we add four uppercase letter A’s (decimal value 65 for ASCII).
01000001 65 01000001 65 01000001 65 01000001 65 -------- 100000100 260
Notice how the value is now bigger than what can be stored in 8 bits. So… to throw the overflow we can take the result and mask it like this
100000100 011111111 ---------- 000000100
That will give us the value 4 which is what we want. The project was in Java and Java does not have unsigned numbers. I know, right, something I never knew until today even after using Java for years. I never really had the need for it.
So, since Java does not have unsigned long data types it was nerve-wracking trying to mask the value when it was set to 32 bits.
I was trying to use this as a mask for the value
long result = value here that is at least 33bits or more. long mask = 0xFFFFFFFF; result = result & mask;
For some reason, Java would flip the number to negative and turn all the most significant bits on.
It turns out all I had to do to fix it was to use L at the end of the hex value for the assignment.
long result = value here that is at least 33bits or more. long mask = 0xFFFFFFFFL; result = result & mask;
I didn’t figure this out on my own. It took someone that had a deeper understanding of the Java numeric types. You can see the discussion below on stack overflow.
I’m not sure if this blog post will help anyone besides me. But it turned out to be an interesting event and I like to record interesting observations for my own personal amusement.