'Purpose of bitwise operation in this example
In the function outb(0x3D5, (uint8_t) (pos & 0xFF));, I am having trouble understanding the purpose of the bitwise operation. pos is a uint16_t variable.
What is the purpose of the bitwise & with simply 8 bits of 1. The & operation would just compare this value with 8 bits of 1, which to my knowledge, would just result in the same value. How does this operation change the value of pos?
For background if it is important, the function outb is intended to move the value of the right argument into the register indexed by the port (left argument). In this case, pos is a position in VGA adapter memory. The function outb uses inline assembly and the assembly instruction out.
Solution 1:[1]
The
&operation would just compare this value with 8 bits of 1s, which to my knowledge, would just result in the same value.
The & operation does not “compare” values. It performs a bitwise AND. When the 16-bit pos is ANDed with 0xFF, the result is the low eight bits of pos. Thus, if pos is 0x1234u, then pos & 0xFF will produce the value of 0x34u.
The conversion to uint8_t with the cast (uint8_t) would produce the same value, because a conversion of an integer to uint8_t wraps the value modulo 28, which, for non-negative integers, is equivalent to taking the low eight bits.
Thus, these expressions all produce the same value:
pos & 0xFF,(uint8_t) pos, and(uint8_t) (pos & 0xFF).
(For negative integers, wrapping modulo 28 and taking the low eight bits are not equivalent if the C implementation uses sign-and-magnitude or one’s complement representations, which are allowed by the C standard but are very rare these days. Of course, no uint16_t values are negative.)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric Postpischil |
