Hexadecimal Problem -Please Help!

sidDug's Avatar, Join Date: Feb 2009
Newbie Member
Hello Friends,
I am facing a peculiar problem Here it is...

I have a hexdecimal integer, eg
Code:
int data = 0x5a0060;
This hexadecimal integer is of the form 0xRRGGBB, which means that "5a" corresponds to RR , "00" to GG and "60" to BB.

Now in the program I want to access the respective integer(or hexa) values of RR, GG and BB. Means I want to extract the respective values of RR, GG, BB components from the input "data" hexadecimal integer. I have spent a lot of time figuring how to separate them( R G and B) , but couldn't find the solution. So friends I request to help me.

(And this 0xRRGGBB as hexadecimal integer is standard input. I can't play with it. )
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Code:
unsigned char RR=(unsigned char)(data >> 16);
0
sidDug's Avatar, Join Date: Feb 2009
Newbie Member
Quote:
Originally Posted by xpi0t0s View Post
Code:
unsigned char RR=(unsigned char)(data >> 16);
yup got it. Thank you xpi0t0s.
In a similar fashion I can get the other hexadecimal integers in GG and BB. Like

Code:
unsigned char RR=(unsigned char)(data >> 8);
unsigned char RR=(unsigned char)(data );
Now one half of the problem is solved. So lemme introduce b4 you the other half.

I will perform average operation on respective RR GG and BB values. (By respective RR GG and BB, I mean that there will be other "data" hexadecimal integer values in the question.) At the end of avg operation I will be left with the individual hexadecimal integer values (from the avg operation). Now I want to club them all back to the "long int data" in hexadecimal integer format. So please guide me how to club char RR GG and BB to long int data.

I'll illustrate with an example.
In the above question it was long int data=0x5A0060; And after conversion, RR='5A',GG='00',BB='60'; now I want to perform the reverse operation. i.e. from RR GG BB to data.
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
It's the exact opposite, cast to a long and shift left:
Code:
unsigned char RR=0x5a, GG=0, BB=0x60;
unsigned long RGBval = ((unsigned long)RR)<<16 | ((unsigned long)GG)<<8 | (unsigned long)BB;
// or
unsigned long RGBval2=RR;
RGBval2=(RGBval2<<8)|GG;
RGBval2=(RGBval2<<8)|BB;
For splitting out the individual components, unsigned char may not be the best choice to use if you're calculating the average; you're likely to overflow those 8 bits.
So you can keep it all as longs just by shifting and ANDing, e.g.
Code:
unsigned long RGBval1=0x5a0060;
unsigned long RGBval2=(RGBval1>>16) & 0xff;
Then RGBval2 contains just the red component and leaves you loads of headroom for any calculations you want to perform.
0
wristbandsnow's Avatar
Newbie Member
Hi friends these thread member are provides proper solution. Why are you doing them. Any reason or any problem for data loaded. If sharing us. Thanks