tags:

views:

126

answers:

3

I'm looking at the original source code for Identicons. There's a bit of code that does some bit twiddling to extract red, green and blue components:

int blue = (code >> 16) & 0x01f;
int green = (code >> 21) & 0x01f;
int red = (code >> 27) & 0x01f;

The code variable is a 32 bit integer.

My question is this: What's the difference between the number 0x01 and 0x01f?

I'm assuming the f means the value is a float, but why make it a float? Is it that the float representation in binary is different to the integer representation? Wouldn't that cause issues for portability reasons when porting if a particular language doesn't use the same representation?

Also, I'm probably reading this wrong on account of not understanding the 0x01f issue, but isn't this just setting the red, green and blue representations to either 0 or 1, depending on the least significant bit?

+6  A: 

That has nothing to do with floats. That's a bitmask.

0x01f = 0b11111

When you & your number with it, it clears all the bits to left of the 5th bit from the right.

Here's how 0x0a2bfb & 0x01f => 0x00001b:

0xfafbff : 0000 1010 0010 1011 1111 1011
0x01f    : 0000 0000 0000 0000 0001 1111 &
----------------------------------------
result   : 0000 0000 0000 0000 0001 1011
NullUserException
+2  A: 

f in the context of hexadecimal is not a float. 0xf is equivalent to decimal 15.

In your example, the code is finding the least significant 5 bits of the color code, likely in a 15 or 16bit color space

Yann Ramin
+2  A: 

I'm not sure about Java, but in C99, hex floats really do exist, and they look like this:

0x50.1p3

The p suffix is mandatory (and is used to indicate the power of 2 to raise the number). Hence, there is no ambiguity with hex integer literals like 0x01f. The compiler won't mistake f for a floating point constant suffix, it'll read it as a hex digit.

Joey Adams
That also works in Java (to my surprise - learned something new!), 0x50.1p3 is equal to 640.5.
Jesper