What you learn today
- Set, clear and test bits
- Masks
- not and negative numbers
Yesterday you saw how many bits a number holds. Today you set, clear and test them one by one. You have known the instructions since week 4: and, or, xor and nor. Back then you used them with 0 and 1. In fact they work on every bit of a number separately.
Bit by bit
| Instruction | bit in the result is 1 if … |
|---|---|
and | both bits are 1 |
or | at least one is 1 |
xor | exactly one is 1 |
nor | both are 0 |
not | the bit was 0 (single input) |
and r0 %1100 %1010 # %1000 = 8
or r1 %1100 %1010 # %1110 = 14
xor r2 %1100 %1010 # %0110 = 6
Masks
A mask is a number whose 1 bits say which places you care about. That gives four moves:
| Goal | Instruction | Example for bit 2 |
|---|---|---|
| set a bit | or with the mask | or r0 r0 %100 |
| clear a bit | and with the inverted mask | not m %100, then and r0 r0 m |
| test a bit | and with the mask, then snez | and r1 r0 %100 |
| toggle a bit | xor with the mask | xor r0 r0 %100 |
not and negative numbers
not flips all bits. 0 does not become 1 but −1, because “all bits 1” means −1 for signed integers. 5 becomes −6. That is not a mistake: not x is always −x − 1.
not is handy for clearing masks. not mask %100 returns a number in which only bit 2 is zero. and with it clears exactly this bit, however long the number is:
not mask %100 # all bits 1 except bit 2
and value value mask # bit 2 cleared
By the way, nor x 0 is the same as not x – both inputs 0 means 1 for nor.
Logical and bitwise and are the same instruction. and r0 2 1 gives 0 although both values are “true”: 2 is %10, 1 is %01, no bit in common. With pure 0/1 values and behaves logically, with other numbers it does not. So turn truth values into 0 or 1 first with snez.
Bit instructions convert decimals into integers first. 5.7 becomes 5 – the fractional part is dropped.
Diagram
Exercise
Task
value (r0) holds a status word. Compute with bit instructions:
set= value with bit 2 setcleared= value with bit 0 cleared (build the mask withnot)tested= 1 if bit 4 is set, otherwise 0flipped= value with bit 1 toggledinverted= all bits of value flipped
Hints
Hint 1
Set with or, toggle with xor, invert with not.
Hint 2
Clear: not mask 1, then and cleared value mask.
Hint 3
Test: and with %1_0000, then snez.
Quiz
5 questions. You pass from 60 % – the server does the grading.
Complete the day
- Passed the simulator exercise
- Passed the quiz with at least 60 %
Without an account progress is saved in this browser only.
Report a mistake in this lesson
Please sign in to report. Sign in