Loading...
A bit pattern can store several independent flags. Apply operations column by column, with a declared width, before interpreting the result as a number or a set of permissions.
What you'll be able to do
A logical left shift moves every bit left and fills new low-order positions with zero. Bits leaving the fixed-width field are discarded. An eight-bit left shift of 10110100 gives 01101000, unsigned 104. The mathematical product 180×2=360 does not fit eight bits, so this stored result is not the full product.
A logical right shift fills high-order positions with zero. Shifting 10110100 right once gives 01011010, unsigned 90. For unsigned values a right shift divides by two with discarded remainder bits. For a signed negative value, zero-filling changes its sign interpretation; an arithmetic right shift instead repeats the sign bit under the given signed model.
Bitwise AND with a zero mask bit clears that position; a one preserves it. AND 00001111 extracts the low four bits of 10110100, giving 00000100. OR with a one forces that position to one, while a zero preserves it. OR 00000010 sets bit 1, producing 10110110.
XOR with one toggles a bit, while zero leaves it unchanged. XOR 00100000 toggles bit 5, producing 10010100. Number bit positions from zero at the right in these examples. A mask can affect several positions at once. Explain whether the requirement is to test, force, clear or toggle; these actions are not interchangeable.
To test whether a flag is set, AND the word with its mask and compare with zero. Testing a group of flags may require comparing with the whole mask if every selected bit must be one. To clear a selected flag, AND with a width-limited mask that has zero at that position and ones elsewhere.
Python integers are not limited to eight bits, so the example applies & 0xFF after a left shift to model eight-bit storage. It does not claim that every programming language handles shifts or overflow identically. Distinguish a bitwise operation across integer bits from logical AND/OR applied to whole Boolean conditions; similar names do not make their value-level effects identical.
value = 0b10110100
print(format(value & 0b00001111, "08b"))
print(format(value | 0b00000010, "08b"))
print(format(value ^ 0b00100000, "08b"))
print(format((value << 1) & 0xFF, "08b"))
print(format(value >> 1, "08b"))Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.