简体   繁体   中英

calculating number of consecutive ones in a binary number using c#

I want for the program to iterate through every possible binary number from 00000000 to 11111111 and I it to calculate the number of consecutive "runs" of ones. Ex) 00000001 and 11100000 both count as a single runs of ones 00001010 and 11101110 both count as two runs of ones

The problem is, is that it ignores the AND mask part and I don't know why.

{
    static void Main(string[] args)
    {
        //Start
        int stuff = BitRunner8();

        //Display
        Console.Write(stuff);
        Console.ReadKey();
    }
    public static int BitRunner8()
    {
        int uniRunOrNot = 0;
        int uniRunCount = 0;
        int uniRunTotal = 0;

        //iterating from numbers 0 to 255
        for (int x = 0; x < 255; x++)
        {
            //I use 128 as my AND mask because 128 is 10000000 in binary
            for ( int uniMask = 128; uniMask != 0; uniMask >>= 1)
            {

                //This is the if statement that doesn't return true ever
                if ((x & uniMask) != 0)

                {
                    //If the and mask is true, and ther were no previous ones before it, add to the the uniRunCount
                    if (uniRunOrNot == 0)
                    {
                        //Total count of the runs
                        uniRunCount++;
                    }
                    // Making it so that if two consective ones are in a row, the 'if' statement right above would return false,
                    //so that it wouldn't add to the uniRunCount
                    uniRunOrNot++;
                }
                else
                {
                    //add the total number of runs to uniRunTotal, and then reset both uniRunOrNot, and uniRunCount
                    uniRunTotal += uniRunCount;
                    uniRunOrNot = uniRunCount = 0;
                }
            }
        }
        //Divide the final amount by 256 total numbers
        uniRunTotal /= 256;
        return uniRunCount;
    }
}

The problem is that your code ignores runs that include the least significant bit. Your code updates uniRunTotal only when it discovers a zero bit. When the least significant bit is non-zero, uniRunCount is never added to the total.

Add code after the loop to add uniRunCount to fix this problem.

You can also fix this issue by applying a sentinel strategy: count bits from the other end, and use nine bits instead of eight, because bit number nine is always zero:

for (int uniMask = 1; uniMask <= 256; uniMask <<= 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM