0

I have a Integer

int RBGcolor = 0xAA3080; //R = AA, G = 30, B = 80

and I want to extract the 0x30 part, so the result should be int Output = 0x30;

How can i do this only with shifting? I thought of something like

int Output = RBGcolor>>2<<2;
Byyo
  • 2,163
  • 4
  • 21
  • 35

1 Answers1

2

Hexadecimal is just a string representation.
An int is still 4 bytes. The 3rd byte forms the G part:

xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
   A        R        G        B

Besides R,G & B, a Color also has an A called the Alpha component which indicates transparency.

There are different ways to isolate the different parts:

(RGBColor << 8) >> 24 or (RGBColor >> 16) & 0xFF

will isolate the R

(RGBColor << 16) >> 24 or (RGBColor >> 8) & 0xFF

will isolate the G

(RGBColor << 24) >> 24 or RGBColor & 0xFF

will isolate the B


Here is a working example, you have to use uint

uint RGB = 0xAA3080;

uint R = RGB << 8 >> 24; //170
uint G = RGB << 16 >> 24; //48
uint B = RGB << 24 >> 24; //128
Byyo
  • 2,163
  • 4
  • 21
  • 35
Dennis_E
  • 8,751
  • 23
  • 29
  • are you sure about R? it's -128 in my case – Byyo May 04 '16 at 07:42
  • If the first bit is 1, right shifting will fill all the shifted bits with 1. I think `(RGBColor >> 16) & 0xFF` is the better option. It will work as it should. – Dennis_E May 04 '16 at 07:53