Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A clarification in Bitwise operator

i am trying to read an image and print the particular color name with respect to its RGBA value (always keeping Alpha value constant).Well this can be achieved with a very complex way but i came across this function on the internet it worked really well but i was unable to understand how this works as i am familiar with only bitwise operator operating on 2 operands.

this is the code

public block(int r, int g, int b)
{
 color = r << 24 | g << 16 | b << 8 | 0xff
}

Can some explain this to me , only thing i could make sense was 0xff hexadecimal is 255 in decimal and an Bitwise OR is taking place.

Thank you

like image 765
Abhishek Madhusudhan Avatar asked Dec 21 '25 02:12

Abhishek Madhusudhan


1 Answers

The << operator is a bit-wise shift. The following table should help you get the gist:

 x  <<  y  ->  base 2 == base 10   explanation
 1      0        1         1       multiply by 2^0 = x1 = shift 0 times
 1      1       10         2       multiply by 2^1 = x2 = shift 1 time
 1      2      100         4       multiply by 2^2 = x4 = shift 2 times
 1      3     1000         8       multiply by 2^3 = x8 = shift 3 times
 3      1      110         6       multiply by 2^1 = x2 = shift 1 time
 5      2    10100        10       multiply by 2^2 = x4 = shift 2 times

So, if you have numbers R, G and B which all fit in 8 bits, and you write their bits, you are doing

  rrrrrrrr 00000000 00000000 00000000 // R << 24: added 24 zeroes
+          gggggggg 00000000 00000000 // G << 16: added 16 zeroes
+                   bbbbbbbb 00000000 // B <<  8: added 8 zeroes
+                            11111111 // 0xff for "fully opaque"
---------------------------------------
  rrrrrrrr gggggggg bbbbbbbb 11111111 // RGBA8, a 32-bit int

Where "+" is equivalent to bitwise "or" when there is no carry and used for the sake of clarity

As Alcanzar notes, you have to be very sure that R, G and B all fit in 8 bits (and, due to internal representation, negative numbers have their highest bit, called the "sign bit", set). Imagine that B were actually larger than 255 - using that formula, its "high" bits would mess up the G and/or R components of the result. If you do not trust your input, you can sanitize each component (R, G and B) with something like

x &= 0xff; // guarantees that only the lowest 8 bits of 'x' can be set
like image 109
tucuxi Avatar answered Dec 22 '25 15:12

tucuxi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!