[英]A loop that works for uint64 and uint32 doesn't work for uint8 or uint16
我想出了一個使用按位運算的循環,從而得到一個數字,該數字每隔一位打開一次(例如,對於8位01010101)。
從理論上講,我的循環應該可以正常工作,並且可以與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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.