3

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?

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334
  • 3
    Why are you worried about the creation of a new `int`? Creating an `int` is free. The part to be concerned about is creation of a new `byte[]` every time. – Gabe Mar 28 '10 at 16:59
  • @gabe: this is just sample code. In the real code, I was assigning to a pre-instantiated class-level byte array. Creating an int is virtually free, but not if you're doing this for hundreds of 320 x 240 arrays. The bit-shifting is significantly faster than BitConverter.ToInt32. – MusiGenesis Mar 28 '10 at 17:03
  • 2
    You're convoluting RGB and BGR here (the two code snippets do not round-trip). – Ben Voigt Mar 28 '10 at 17:23
  • Creating an int isn't "virtually" free -- it's completely free. BitConverter isn't slow. Putting the bytes into the array and making the functino call is what's slow. – Gabe Mar 28 '10 at 17:52
  • I finally did some benchmarking on this: http://stackoverflow.com/questions/4326125/faster-way-converter-byte-array-to-int/4331638#4331638 It seems that the function call overhead of `BitConverter` is fairly significant. – Gabe Dec 02 '10 at 06:13

2 Answers2

9
int i = (B << 0) | (G << 8) | (R << 16);
dtb
  • 213,145
  • 36
  • 401
  • 431
4

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

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536