What you learn today
- Shift left and right
- Logical or arithmetic
- Shifting as multiplication
Yesterday you set, cleared and tested bits with and, or and xor. Today you move them. Four instructions shift all bits of a number by a number of places:
| Instruction | does |
|---|---|
sll r? a n | shifts a left by n places, zeros come in on the right |
sla r? a n | the same as sll – in the game it is the same operation |
srl r? a n | shifts right, zeros come in on the left |
sra r? a n | shifts right, the sign comes in on the left |
Shifting is arithmetic
One place to the left doubles a number, one place to the right halves it and cuts off the remainder:
move r0 %0000_0101 # 5
sll r1 r0 3 # %0010_1000 = 40, i.e. 5 * 8
srl r2 r1 2 # %0000_1010 = 10, i.e. 40 / 4
With decimals this does not work: before every bit instruction the chip converts the value into an integer, the fractional part is dropped.
Logical or arithmetic?
For positive numbers srl and sra are the same. For negative numbers they are not: negative numbers have ones all the way on the left. sra shifts those ones in – the sign stays, −64 becomes −16. srl shifts in zeros and turns a small negative number into a huge positive one.
move r3 -64
sra r4 r3 2 # -16
Memory aid: a as in arithmetic – calculates with the sign. l as in logical – just moves bits.
Pulling out fields
Often several small values live in one number, say four bits for a state starting at bit 4. First shift right, then cut off with a mask:
srl r5 r0 4 # bit 4 slides down to bit 0
and r5 r5 %1111 # keep only the lower four bits
The day after tomorrow you learn ext, which does exactly these two steps in one. But you only understand how it works inside with srl and and.
Bit instructions work on 64-bit integers, but registers store decimal numbers with 53 bits of precision. Anything beyond 53 bits does not come back unchanged.
Diagram
Exercise
Task
r0 holds a positive integer, r5 a negative one (set by the test). Without mul and div:
r1= r0 · 8r2= r0 / 4 (rounded down)r3= r5 / 4 keeping the signr4= bits 4 to 7 of r0 as a number from 0 to 15
Hints
Hint 1
Times 8 is three places left: sll r1 r0 3.
Hint 2
Divided by 4 is two places right – for r5 with sra so the sign stays.
Hint 3
Bits 4 to 7: first srl r4 r0 4, then and r4 r4 %1111.
Quiz
4 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