Question

I want to remove the last set bit of a ulong. Here's what I do:

ulong mydata;
...
ulong t = 1;
for (int i = 0; i < ulongSizeBits; i++)
{
    if ((myData&t)!=0)
    {
        mydata = mydata & (~t);
        break;
    }
    t <<= 1;
}

The problem is that this doesn't work as advertised. Let's do another experiment:

        var test = 1U;
        var t1 = ~test;
        var t = 1;
        for (int i = 0; i < 64; i++)
        {
            Console.Write((t&t1)!=0?1:0);
            t <<= 1;
        }

The output will be not 01111111111111111111111111111111111111111111111111111111111111 as expected, but 0111111111111111111111111111111100000000000000000000000000000000. It appears, that bitwise not converts ulong to uint or something.

What is the best way to work around this?

Was it helpful?

Solution

1U is not ulong. It's uint. Declare test and t as ulong and you'll get what you need:

var test = 1UL;
var t1 = ~test;
var t = 1UL;
for (int i = 0; i < 64; i++)
{
    Console.Write((t & t1) != 0 ? 1 : 0);
    t <<= 1;
}

prints

01111111111111111111111111111111111111111111111111111111111111
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top