【问题标题】:how to convert a byte to 4 bytes to be used as color in c#?如何将一个字节转换为 4 个字节以在 c# 中用作颜色?
【发布时间】:2019-09-19 21:54:07
【问题描述】:

我需要将一个字节转换为 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);

我尝试使用按位运算符,但我不太擅长。

【问题讨论】:

    标签: c#


    【解决方案1】:

    您可以使用位运算符。

    byte input = ...;
    r = input & 0x3; // bits 0x1 + 0x2
    g =( input & 0xc) >> 2; // bits 0x4 + 0x8
    b = (input & 0x30) >> 4; //bits 0x10 + 0x20
    

    按位运算符& 对输入进行按位和。 >> 将数字向右移动给定的位数。

    或者如果“第一和第二”位是指最高两位,您可以如下获取它们

    r = input >> 6;
    g = (input >> 4) & 0x3;
    b = (input >> 2) & 0x3;
    

    【讨论】:

    • 感谢您的帮助,但您能告诉我如何获取最后 2 位的内容吗?
    • 取决于你所说的“最后一位”(即最左边或最右边)是input >> 6input & 0x3
    【解决方案2】:

    您可能希望将 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}");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-05-04
      • 1970-01-01
      • 2013-01-14
      • 2011-02-19
      • 2012-12-15
      • 2019-10-11
      相关资源
      最近更新 更多