【发布时间】:2022-06-27 17:25:32
【问题描述】:
有人可以解释下面的binary_printf 功能吗?
什么是 mask 和 shift 以及它是如何工作的:
byte = (value & mask) / shift; // Isolate each byte.
我认为它总是给'0'是没用的,还要解释if-else声明byte & 0x80... 一起解释我整个代码?我从乔恩·埃里克森名著黑客:剥削的艺术。用最简单的话解释一下。
void binary_print(unsigned int value)
{
unsigned int mask = 0xff000000; // Start with a mask for the highest byte.
unsigned int shift = 256 * 256 * 256; // Start with a shift for the highest byte.
unsigned int byte, byte_iterator, bit_iterator;
for (byte_iterator = 0; byte_iterator < 4; byte_iterator++)
{
byte = (value & mask) / shift; // Isolate each byte.
printf(\" \");
for (bit_iterator = 0; bit_iterator < 8; bit_iterator++)
{ // Print the byte\'s bits.
if (byte & 0x80) // If the highest bit in the byte isn\'t 0,
printf(\"1\"); // print a 1.
else
printf(\"0\"); // Otherwise, print a 0.
byte *= 2; // Move all the bits to the left by 1.
}
mask /= 256; // Move the bits in mask right by 8.
shift /= 256; // Move the bits in shift right by 8.
}
}
-
每一行都有注释——你不明白吗?
-
// Isolate each byte.没用,它总是给\'0\'。事实并非如此。如果您printf(\"%02X \", byte);,您会看到每个字节的正确值。
标签: c binary bit-manipulation bitwise-operators bit-shift