匹配数字中的一系列位,然后将匹配转换为零?

时间:2016-04-29 04:23:38

标签: c#

我的任务是搜索数字的二进制表示,并替换数字的另一个二进制表示的匹配模式。如果我得到匹配,我将第一个整数的匹配位转换为零并继续。 例如,数字469将是meteor add http,我必须将其与5(111010101)匹配。这是我迄今为止编写的程序。没有按预期工作。

101

1 个答案:

答案 0 :(得分:2)

少数事情:

  1. 使用uint。在处理二进制数时,使事情变得更加容易。
  2. 你并没有真正设置任何东西 - 你只是存储信息,这就是你经常打印相同数字的原因。
  3. 你应该循环x次,其中x =二进制字符串的长度(不仅仅是29)。没有内循环
  4. static void Main(string[] args)
    {
        //this is the number I'm searching for a match in
        uint binaryTicket = 469;
        //This is the pattern I'm trying to match (101)
        uint binaryPerforator = 5;
    
        var numBinaryDigits = Math.Ceiling(Math.Log(binaryTicket, 2));
        for (var i = 0; i < numBinaryDigits; i++)
        {
            var perforatorShifted = binaryPerforator << i;
    
            //We need to mask off the result (otherwise we fail for checking 101 -> 111)
            //The mask will put 1s in each place the perforator is checking.
            var perforDigits = (int)Math.Ceiling(Math.Log(perforatorShifted, 2));
            uint mask = (uint)Math.Pow(2, perforDigits) - 1;
    
            Console.WriteLine("Ticket:\t" + GetBinary(binaryTicket));
            Console.WriteLine("Perfor:\t" + GetBinary(perforatorShifted));
            Console.WriteLine("Mask :\t" + GetBinary(mask));
    
            if ((binaryTicket & mask) == perforatorShifted)
            {
                Console.WriteLine("Match.");
                //Imagine we have the case:
    
                //Ticket:
                //111010101
                //Perforator:
                //000000101
    
                //Is a match. What binary operation can we do to 0-out the final 101?
                //We need to AND it with 
                //111111010
    
                //To get that value, we need to invert the perforatorShifted
                //000000101
                //XOR
                //111111111
                //EQUALS
                //111111010
    
                //Which would yield:
                //111010101
                //AND
                //111110000
                //Equals
                //111010000
    
                var flipped = perforatorShifted ^ ((uint)0xFFFFFFFF);
                binaryTicket = binaryTicket & flipped;
            }
        }
    
        string binaryTicket01 = Convert.ToString(binaryTicket, 2);
        Console.WriteLine(binaryTicket01);
    }
    
    static string GetBinary(uint v)
    {
        return Convert.ToString(v, 2).PadLeft(32, '0');
    }
    

    请仔细阅读以上代码 - 如果您有任何不明白之处,请给我留言,我可以和您一起完成。