- Some devices have unused bits on the right (least-significant) side that must be discarded.
- Discarding is accomplished with right shift (>>) in languages that support bit shift
operations.
- In situations where left shift is needed, or if sign-extend can't be avoided, you can mask
unwanted bits to remove them. Masking is best accomplished with bitwise AND. The
mask is a constant which has the bits that need to be retained set to logic 1.
For example, a mask of 0xF is equivalent to 0b1111, and retains only the four
least significant bits.
/* right shift */
unsigned char x = 0x23;
unsigned char y = x >> 4;
/* y is 0x02 */
/* mask to discard bits */
unsigned char z = x & 0xF;
/* z is 0x03 */
- In Excel, multiply and divide operations can be equivalent to left and right
shift. For example, multiply times 23 is equivalent to left shift 3.
Right shift can be accomplished with *2-b or /2b. When
right shifting this way, the result must be rounded to a whole number to discard
the low bits. The INT() function is used here to round down.
- BITAND() can be used for masking, but beware this takes decimal input and provides decimal
output. This can make BITAND() confusing to use for masking. BITAND() works with
at least 32 bits, similar to HEX2DEC().
- The following Excel example demonstrates the same
shift and discard operations on 0x23 as illustrated in the other language
examples. Note that in this example, Excel is showing the decimal result in
Column C. Our result coincidentally appears the same in decimal as the result
does if displayed in hex as seen is in the other examples. Row 1 is the shift
while row 2 is the discard operation.
Table 3-5 Excel Example for Discarding Bits | A | B | C |
---|
1 | 23 | =HEX2DEC(A1) | =INT(B1*2^-4) |
2 | 23 | =HEX2DEC(A2) | =BITAND(B2,HEX2DEC("F")) |
Table 3-6 Excel Calculation Result for Discarding Bits
|
A |
B |
C |
1 |
23 |
35 |
2 |
2 |
23 |
35 |
3 |
- JavaScript and Python support shift as well as
bitwise AND.
/* JavaScript */
/* right shift */
let x = 0x23
let y = x >> 4
/* y is 0x2 */
/* mask to discard bits */
let z = x & 0xF
/* z is 0x3 */
# Python
# right shift
x = 0x23
y = x >> 4
# y is 0x2
# mask to discard bits
z = x & 0xF
# z is 0x3