【问题标题】:A loop that works for uint64 and uint32 doesn't work for uint8 or uint16适用于 uint64 和 uint32 的循环不适用于 uint8 或 uint16
【发布时间】:2013-10-21 13:35:54
【问题描述】:

我想出了一个使用按位运算的循环,产生一个每隔一个位打开的数字(即在 8 位的情况下,01010101)。

理论上,我的循环应该可以正常工作,并且可以正常工作 uint32uint64,但不能正常工作 uint8uint16。我想知道为什么...

代码如下:

@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;

【问题讨论】:

  • 欢迎来到 SO!你能提供更多关于什么不起作用的信息吗?你看到了什么输出?
  • 谢谢德里克。上面的代码工作正常,但是如果我用 uint8 或 uint16 替换 uint32,整个代码就会进入无限循环。我不太明白为什么...
  • 失败很可能是由于小于 int 的变量的整数提升。
  • 如果a 的类型小于int~a != (a &lt;&lt; 1) 始终为真。
  • 感谢您的回答.. 但是可以详细说明一下吗?我是新手。为什么 ~a != (a

标签: objective-c bit-manipulation uint32


【解决方案1】:

“小于 int” starblue 表示sizeof(a) &lt; sizeof(int)。由于integer promotion rule,比 int 窄的类型在执行操作之前总是提升为 int。更多信息请阅读Implicit type promotion rules

因此,如果 a 是 uint8uint16~a 的最高位将始终为 1,并且永远不能等于 a &lt;&lt; 1

例如,如果 a 是 uint16,运行几次迭代我们就有 a = 0x5555。在那之后

(int)a = 0x00005555
    ~a = 0xFFFFAAAA
a << 1 = 0x0000AAAA

如您所见,~a != (a &lt;&lt; 1) 和程序将永远循环

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多