Home:ALL Converter>A loop that works for uint64 and uint32 doesn't work for uint8 or uint16

A loop that works for uint64 and uint32 doesn't work for uint8 or uint16

Ask Time:2013-10-21T21:35:54         Author:funct7

Json Formatter

I came up with a loop using bitwise operation, resulting in a number that has every other bit turned on (i.e. in case of 8-bit, 01010101).

In theory, my loop should work just fine, and it does work fine with uint32 and uint64, but not uint8 or uint16. I wonder why...

Here's the code:

@autoreleasepool {
    // a = 00000000
    uint32 a = 0;
    // b = 11111111
    uint32 b = ~a;
    // a = 11111111
    a = ~a;

    // if (a = 01010101) ~a = 10101010, a << 1 = 10101010
    while (~a != (a << 1)) {
        // 1st time: a << 1 = 11111110 = a
        // 2nd time: a << 1 = 11111010 = a
        a = a << 1;
        // 1st time: ~a = 00000001 = a
        // 2nd time: ~a = 00000101 = a
        a = ~a;
        // 1st time: a << 1 = 00000010 = a
        // 2nd time: a << 1 = 00001010 = a
        a = a << 1;
        // 1st time: b ^ a = 11111101 = a
        // 2nd time: b ^ a = 11110101 = a
        a = b ^ a;
    }

    NSLog(@"%x", a);
    NSLog(@"%u", b);



    // Apply the same loop to a bigger scale
    uint64 x = 0x0;
    uint64 y = ~x;
    x = ~x;

    while (~x != (x << 1)) {
        x = x << 1;
        x = ~x;
        x = x << 1;
        x = y ^ x;
    }

    NSLog(@"%llx", x);
    NSLog(@"%llu", x);
}
return 0;

Author:funct7,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/19496061/a-loop-that-works-for-uint64-and-uint32-doesnt-work-for-uint8-or-uint16
yy