Implementing rotate left using AND, NOT, and ADD operations
I'm implementing a 16-bit bit shifter to rotate bits to the left by r. I only have access to the AND
, NOT
and ADD
operations. There are 3 condition codes: negative, zero and positive, which are set when you use any of these operations.
This is my approach:
AND
the number with1000 0000 0000 0000
to set condition codes to positive if the most significant bit is1
.ADD
the number with itself. This shi开发者_运维问答fts bits to the left by one.- If the MSB was
1
,ADD
1
to the result. - Loop through steps (1)-(3) r times.
Are there any other efficient ways I can do this?
Since this is homework, I'll help you think about it.
2 * 2 = 4
4 * 2 = 8
8 * 2 = 16
0010 * 0010 = 00100
0100 * 0010 = 01000
1000 * 0010 = 10000
A left shift is a [some unknown] operation. That [some unknown] operation can be implemented using AND, NOT and ADD by doing...
Here's some x86 code to get you started:
; I'm assuming the number you want to rotate is in ax
; I'm assuming the number of bits to rotate is in cx
loop_start:
add cx, -1 ; Can only use add, so add -1
jo loop_end ; If cx is < 0
mov bx, ax ; Copy ax into bx
add ax, ax ; shift ax left 1 bit
and bx, 1000000000000000b ; Test the msb of bx
jz loop_start ; if the msb is zero, jump
add ax, 1 ; if the msb is one, add one to ax
jmp loop_start ; Loop
loop_end:
精彩评论