Whats the use of "&" , 0x000000FF , >> 8?

-3

Whats the use of &, 0x000000FF and >> 8 in the following method. Can any one explain?

Thanks in advance

(UIColor *)UIColorFromIntegerCode:(int)integerCode  {    
    CGFloat r = (integerCode & 0x000000FF) / 255.0f;
    CGFloat g = ((integerCode & 0x0000FF00) >> 8) / 255.0f;
    CGFloat b = ((integerCode & 0x00FF0000) >> 16) / 255.0f;

    return [UIColor colorWithRed:r green:g blue:b alpha:1.0f];
}
ios
objective-c
hex
uicolor
asked on Stack Overflow May 30, 2018 by Dhanush • edited May 30, 2018 by Robert Andrzejuk

1 Answer

2

Note: There is a little bug in your. Here is the edited version:

- (UIColor *)UIColorFromIntegerCode:(int)integerCode  {
    CGFloat b = (integerCode & 0x000000FF) / 255.0f;
    CGFloat g = ((integerCode & 0x0000FF00) >> 8) / 255.0f;
    CGFloat r = ((integerCode & 0x00FF0000) >> 16) / 255.0f;

    return [UIColor colorWithRed:r green:g blue:b alpha:1.0f];
}

Explanation:

& is the Bitwise AND Operator: It takes two numbers and performs AND operation on every bit. The resultant bit is 1 if both bits are 1 otherwise 0.

>> is the Bitwise Right Shift Operator: It takes two numbers. First is the number that will be shifted. Second is the places to shift.

0x000000FF is the hexadecimal representation of blue color. Performing a bitwise AND between integerCode and 0x000000FF filters the blue bits from the integerCode and assigns it to float b.

Similarly 0x0000FF00 is the hex of green and 0x00FF0000 is the hex of red.

Notice the shifting of FF between the three hex values.

0x000000FF
0x0000FF00 (shifted 8 bits right)
0x00FF0000 (shifted 16 bits right)

The bitwise right shift operator is used to adjust this shifting of bits. Finally filtered value is divided with 255 to make it between 0 and 1. (255 is the maximum value a particular color can have.)

After filtering the colors in r, g and b, they are provided to UIColor method to create a UIColor.

If you are further interested in the details of bitwise operators, here is a good resource.

answered on Stack Overflow May 30, 2018 by HAK • edited May 30, 2018 by HAK

User contributions licensed under CC BY-SA 3.0