Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I did not study software at uni, I did physics, so i've never really got to grips with bits, bytes and bit shifting, and it has fortunately not cropped up very often. However, I now need to do something that I am stuck on how to start.

I have four decimal integers that describe a colour for display on a GUI. I need to convert these into a hex number in the format 0xTTRRGGBB. TT is transparency, RR is red, GG is green, BB is blue. Each of these values can be 0-FF in hex, so my decimal values are 0-255.

Could somebody help me with this please? I know that a number is not really hex or decimal, as it is ultimately stored in bits on the PC and whether or not it is diplayed to me in hex or dec is irrelevant as far as the code is concerned. So I guess I can just bit-shift the decimal values then add(?) them - is that right?

So far, I have tried this:
int redVal = 255; // in hex is 0x000000FF
redVal << 2; // I thought this would change redVal to 0x0000FF00, but in debug //mode, this line is skipped over and redVal remains as 0x000000FF - why is this?


Any help, very gratefully received.
Posted
Comments
Mohibur Rashid 29-Oct-12 5:55am    
The reason debugger skipped that part because you did not store that value any where. As OrginalGriff shows, store it somewhere.
Jackie Lloyd 29-Oct-12 5:58am    
yeah, thanks, I just spotted that and was about to update my answer but you beat me to it! Thankyou :)

No, not quite! :laugh:
x << 2 only shifts the value by two bits - the equivalent of multiplying it by 4 ( by 2 for each bit shifted, since each bit can have two values).

If you want to change 0x00FF to 0xFF00, then you need to shift it by 8 bits:
C++
int x = 0x00FF << 8;
- the equivalent of multiplying it by 256!
 
Share this answer
 
Comments
Jackie Lloyd 29-Oct-12 6:00am    
ahhh - I see now, thankyou so much, it seems so obvious now but I'd never had solved it by myself.
OriginalGriff 29-Oct-12 6:04am    
You're welcome!
Quote:
int redVal = 255; // in hex is 0x000000FF
redVal << 2; // I thought this would change redVal to 0x0000FF00, but in debug //mode, this line is skipped over and redVal remains as 0x000000FF - why is this?


The result of redVal << 2 is 0x000003FC (as noted by our Original two bits are shifted, not two hex digits), but you never see that because it's a temporary (you didn't assign it).
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900