views:

310

answers:

2

I'm using BitConverter.ToInt32 to pack 3 byte values into an int, like so:

byte R = 0;
byte G = 0;
byte B = 0;
int i = BitConverter.ToInt32(new byte[] { R, G, B, 0 }, 0);

Is there a faster way to do this that doesn't involve the creation of a new int each time? Getting the bytes out of an int is easy:

int i = 34234;
byte B = (byte)(i >> 0);
byte G = (byte)(i >> 8);
byte R = (byte)(i >> 16);

Is there a simple way to reverse this process and use bit-shifting to write the RGB bytes back over an existing int?

+7  A: 
int i = (B << 0) | (G << 8) | (R << 16);
dtb
Shifting by 0 is not really necessary.
IVlad
The winner - but I can't accept for another 9 minutes.
MusiGenesis
Love the Lemmings avatar, by the way. I think I mentioned that before.
MusiGenesis
@IVlad: But it makes the code much better to read, at no cost.
Henk Holterman
This undoes the bit-shifting shown, which is in BGR(A) format. But it isn't equivalent to the BitConverter snippet, which uses RGB(A) format.
Ben Voigt
+4  A: 

You ought to consider the Color structure. It has R, G and B properties and FromArgb() and ToArgb() methods.

Hans Passant
You'd think `Color` would be ideal for this, but it's piggishly slow.
MusiGenesis
Hard to see how it could be, it uses simple shifts, and and or, just like regular code.
Hans Passant
Try it for yourself.
MusiGenesis
I can confirm Musi's findings. Color.FromRgb is even slower than the BitConverter.
Henk Holterman