Alternative to BitConverter.ToInt32
-
22-09-2019 - |
Question
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
?
Solution
int i = (B << 0) | (G << 8) | (R << 16);
OTHER TIPS
You ought to consider the Color structure. It has R, G and B properties and FromArgb() and ToArgb() methods.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow