【问题标题】:Cannot apply bit mask无法应用位掩码
【发布时间】:2014-07-25 01:22:33
【问题描述】:

我正在制作一个马程序。我有马脸,想涂一点面膜。佩戴位掩码时,只能看到马眼。首先,我必须将马脸转换为数字。为此,我有一组位,其中包括马脸的 0、0、0 和 1。

我正在使用 C# 并将问题分解为多个部分:

  1. 将马头转换为数字格式
  2. 为其佩戴一个位掩码
  3. 把位掩码放在马上
  4. 转换数字蒙面马背 进入图形

在第 4 步,我希望只看到马眼,但我只看到“0”,这甚至不是马脸。

这是我所有的代码,请不要质疑我的 ASCII 艺术与问题无关,除了它是一个原型,真正的程序会有更好的图形。

//the head of the horse
string head = "#      #" +
              "########" +
              "#O    O#" +
              "#      #" +
              "#      #" +
              "#=    =#" +
              " #====# " +
              "  ####  ";
//digitize the horse into bits of binary
string binaryHead = head.Replace('#', '0').Replace('=', '0').Replace(' ', '0').Replace('O', '1');
long face = Convert.ToInt64(binaryHead, 2);

//make a bit mask with holes for the eyes
string mask = "11111111" +
              "11111111" +
              "10111101" +
              "11111111" +
              "11111111" +
              "11111111" +
              "11111111" +
              "11111111";

//apply the bit mask using C#
long maskBits = Convert.ToInt64(mask, 2);
string eyesOnly = Convert.ToString(face & maskBits, 2);
//eyesOnly is "0"....WHAT??? It should be more than that. WHERE IS THE HORSE??
//It should look like this:
//              "00000000" +
//              "00000000" +
//              "01000010" +
//              "00000000" +
//              "00000000" +
//              "00000000" +
//              "00000000" +
//              "00000000";

我怀疑转换有问题,我尝试了各种方法,例如转换为字节数组并用空格格式化字符串,但没有运气。我想知道这个问题是否可能是 NP 难题。

【问题讨论】:

  • @Vadim-Kotov 你编辑了 SO 上最好的问题标题之一,耻辱
  • @Gareth 好吧,也许吧。但是这样的事情在 Meta SO 上更合适:)

标签: c# binary bit digital


【解决方案1】:

faceeyesOnly 没有共同的 1 位。 maskBits 留下一切除了的眼睛。交换01,或使用~ 运算符翻转maskBits。并给它一个更好的名字,以便清楚什么它是一个掩码:bitmaskForNotEyes

【讨论】:

    【解决方案2】:

    我认为问题是-

    string binaryHead = head.Replace('#', '0').Replace('=', '0').Replace(' ', '0').Replace('O', '1');
    
    1. 首先,将'#'全部改为'0'
    2. 然后所有'='都改成'0'
    3. 所有' ' 都更改为'0'
    4. 终于看到'1'

    所以,转换后头部看起来像这样 -

    string head = "00000000" +
                  "00000000" +
                  "01000010" +
                  "00000000" +
                  "00000000" +
                  "00000000" +
                  " 000000 " +
                  "  0000  ";
    

    现在你正在用它做& -

    string mask = "11111111" +
                  "11111111" +
                  "10111101" +
                  "11111111" +
                  "11111111" +
                  "11111111" +
                  "11111111" +
                  "11111111";
    

    所以输出显然是0

    【讨论】:

    • 头部字符串中的空格为'0'。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多