Reputation: 11
I need to convert a byte to 4 bits so it can be used as a color.
byte input;
byte r = //the first and second bits of input ;
byte g = //the third and forth bits of input ;
byte b = //the fifth and sixth bits of input ;
Color32 output = new Color32(r,g,b);
I tried working with bit-wise operators but i am not very good at them .
Upvotes: 0
Views: 322
Reputation: 17382
You can use bitwise operators.
byte input = ...;
r = input & 0x3; // bits 0x1 + 0x2
g =( input & 0xc) >> 2; // bits 0x4 + 0x8
b = (input & 0x30) >> 4; //bits 0x10 + 0x20
The bitwise operator &
makes a bitwise and on the input. >>
shifts a number to the right by the given number of bits.
Or if by "first and second" bit mean the highest two bits, you can get them as follows
r = input >> 6;
g = (input >> 4) & 0x3;
b = (input >> 2) & 0x3;
Upvotes: 2
Reputation: 25070
You probably want 11 binary to map to 255 and 00 to map to 0 to get a maximum spread in color values.
You can get that spread by multiplying the 2 bit color value by 85. 00b stays 0, 01b becomes 85, 10b becomes 190 and 11b becomes 255.
So the code would look something like this
byte input = 0xfc;
var r = ((input & 0xc0) >> 6) * 85;
var g = ((input & 0x30) >> 4) * 85;
var b = ((input & 0x0c) >> 2) * 85;
Console.WriteLine($"{r} {g} {b}");
Upvotes: 0