Att*_*lah 2 .net c c# binary bit-manipulation
我有一个二进制数1011011,我怎么能一个接一个地遍历所有这些二进制数字?
我知道如何使用modulo和division对十进制整数执行此操作.
int n = 0x5b; // 1011011
Run Code Online (Sandbox Code Playgroud)
真的,你应该这样做,一般十六进制表示更好:
printf("%x", n); // this prints "5b"
Run Code Online (Sandbox Code Playgroud)
要获得二进制文件(重点是易于理解),请尝试以下方法:
printf("%s", "0b"); // common prefix to denote that binary follows
bool leading = true; // we're processing leading zeroes
// starting with the most significant bit to the least
for (int i = sizeof(n) * CHAR_BIT - 1; i >= 0; --i) {
int bit = (n >> i) & 1;
leading |= bit; // if the bit is 1, we are no longer reading leading zeroes
if (!leading)
printf("%d", bit);
}
if (leading) // all zero, so just print 0
printf("0");
// at this point, for n = 0x5b, we'll have printed 0b1011011
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6062 次 |
| 最近记录: |