0
我想出了一個使用按位運算的循環,產生一個數字,每隔一位打開一個數字(即,在8位的情況下,01010101 )。一個適用於uint64和uint32的循環對於uint8或uint16不起作用
從理論上講,我的循環應該工作得很好,並且它對uint32和uint64,但不是uint8或uint16可以正常工作。我不知道爲什麼......
下面的代碼:
@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!你能否提供更多有關哪些實際工作沒有的信息?你看到了什麼輸出? – Derek
謝謝德里克。上面的代碼工作正常,但如果我用uint8或uint16替換uint32,則整個代碼會進入無限循環。我不明白爲什麼...... – BridgeTheGap
失敗最可能是由於整數提升小於int的變量。 –