如何将一个字节转换为4个字节以用作c#中的颜色?
我需要将一个字节转换为4位,这样它就可以用作颜色如何将一个字节转换为4个字节以用作c#中的颜色?,c#,C#,我需要将一个字节转换为4位,这样它就可以用作颜色 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); 我试过使用位运算符,但我不太擅长。您可以使用位运算符 by
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);
我试过使用位运算符,但我不太擅长。您可以使用位运算符
byte input = ...;
r = input & 0x3; // bits 0x1 + 0x2
g =( input & 0xc) >> 2; // bits 0x4 + 0x8
b = (input & 0x30) >> 4; //bits 0x10 + 0x20
位运算符&
在输入端进行位and运算>
将数字向右移位给定位数
或者,如果“第一位和第二位”表示最高的两位,则可以按如下方式获得它们
r = input >> 6;
g = (input >> 4) & 0x3;
b = (input >> 2) & 0x3;
可以使用位运算符
byte input = ...;
r = input & 0x3; // bits 0x1 + 0x2
g =( input & 0xc) >> 2; // bits 0x4 + 0x8
b = (input & 0x30) >> 4; //bits 0x10 + 0x20
位运算符&
在输入端进行位and运算>
将数字向右移位给定位数
或者,如果“第一位和第二位”表示最高的两位,则可以按如下方式获得它们
r = input >> 6;
g = (input >> 4) & 0x3;
b = (input >> 2) & 0x3;
您可能希望11二进制映射为255,00映射为0,以获得颜色值的最大排列 您可以通过将2位颜色值乘以85来获得该排列。00b保持为0,01b变为85,10b变为190,11b变为255 所以代码看起来像这样
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}");
您可能希望11二进制映射为255,00映射为0,以获得颜色值的最大排列 您可以通过将2位颜色值乘以85来获得该排列。00b保持为0,01b变为85,10b变为190,11b变为255 所以代码看起来像这样
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}");
谢谢你的帮助,但是你能告诉我如何获取最后2位的内容吗?取决于你所说的“最后一位”(即最左边或最右边)是
input>>6
还是input&0x3
,谢谢你的帮助,但是你能告诉我如何获得最后2位的内容吗?取决于你所说的“最后一位”(即最左边或最右边)的意思,它是input>>6
或input&0x3