Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explaining Bitwise shifting aRGB values in Java

Tags:

java

I was wondering the meaning of "Bitwise Shifting". Currently I am trying to create Image Filters in Java using BufferedImage. I found some good answers on how to access the RGB values individually in other posts but wasnt exactly sure on how it works. I understand the RGB values are stored in a 32-bit int each 8-bit part representing the value.

This is what I was looking at: a link

Basically looking for someone to explain this process, the Google searches Ive done were too technical.

like image 831
0xOffset Avatar asked Dec 31 '25 04:12

0xOffset


2 Answers

When you have a single integer that contains multiple bytes of information, then masking and shifting are the processes used to access the individual pieces. Assuming the bytes are stored like such (they probably aren't, but...) then this is what you could do to retrieve them:

aRGB: 255, 65, 33, 17
binary: 11111111 01000001 00100001 00010001

To retrieve the red value (65) from a variable x:

x && 0x00FF0000

  11111111 01000001 00100001 00010001
* 00000000 11111111 00000000 00000000
-------------------------------------
  00000000 01000001 00000000 00000000

Then the shifting operation, to move the bits to where they make sense as a lone value:

00000000 01000001 00000000 00000000 >> 16 = 00000000 00000000 00000000 01000001

The binary mask captures only the second byte of the value, by setting all the other bits to 0; only the bits that match the second byte remain as they are (multiplied by 1, not 0). Then, you shift the bits to the right 16 places, to strip off those extra 0's. Obviously, the leading 0's no longer matter, so the result is just a plain binary 01000001, or decimal 65.

like image 93
Myrddin Emrys Avatar answered Jan 02 '26 19:01

Myrddin Emrys


It is technical in nature. You store a value 0 - 255, or in binary:

from
00000000
to
11111111

then you take a larger container like this one:

0000000000000000

and insert it there so if your color is 117

0000000001110101

and shift it to the left one byte so you get

0111010100000000

then you add the second color, say it 65 or 01000001 and get

0111010101000001

then you again shift it one byte to the left and get

011101010100000100000000

at last you add the third color and its for example a 255 or 11111111 you get

011101010100000111111111

so you have stored three values 0 - 255 via bitshift.

like image 26
Angelo Fuchs Avatar answered Jan 02 '26 19:01

Angelo Fuchs