Assembly language programming
Store a value in ax. Create a loop that "displays" the bits in ax. The word "displays" means to put the bits into another register. Values in the other register must be only 0 or 1.
I am doing it like this but I don't know I am doing it correctly or not. Please help.
.data
x:
.word 0b00101
.text
.globl _start
_start:
movw x, %ax
loop:
cmp %ax, %bx
je done
andw 0b1000000000000000, %ax
shl $1, %ax
jmp loop
done:
nop
Please use
SHL
, andAND
instruction only
The trouble with this kind of condition is that we can't know what other instructions you are allowed to use. Your own example already uses MOV
, CMP
, JE
, JMP
, and even NOP
.
Because the task asks for a loop with precisely 16 iterations, it's clear that it's just impossible to only use SHL
and AND
. We need at the very least a conditional jump and use an independent iteration counter.
The basic idea is always that SHL
puts the bit that it shifts out, in the carry flag. From there, an instruction like ADC
can pick it up and produce the result BX=1
.
; IN (ax)
mov cx, 16
again:
xor bx, bx ; BX=0
shl ax, 1 ; -> CF
adc bx, bx ; BX=[0,1]
loop again
Now I'll remove those XOR
, ADC
, and LOOP
instructions that you yourself didn't use. This example only uses MOV
, SHL
, and JNC
:
; IN (ax)
mov cx, 1
again:
mov bx, 0
shl ax, 1
jnc cont
mov bx, 1
cont:
shl cx, 1 ; Produces CF=1 after 16 iterations
jnc again
Provided that the value in AX
has its lowest bit set (like in your example 0b00101), we can do without the independent iteration counter.
; IN (ax)
again:
mov bx, 0
shl ax, 1
jnc cont \
mov bx, 1 | These don't change flags
cont: /
jnz again ; Still based on the flags from `shl ax, 1`
What will happen if you use this snippet on an AX
value that does not have its lowest bit set, is that the loop will have less than 16 iterations!
And if you feel the urge to use the AND
instruction at least once, you can use it to clear the BX
register:
; IN (ax)
mov cx, 1
again:
and bx, 0 ; ANDing BX with zero produces BX=0
shl ax, 1 ; -> CF now has the bit that was shifted out at the high end of AX
jnc cont ; That bit was 0, so BX=0 is fine
mov bx, 1 ; Else make BX=1
cont:
shl cx, 1 ; Produces carry after 16 iterations
jnc again
On successive iterations CX
will hold 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 0
When the value finally becomes 0, the CF will get set because the true result of doubling the value (65536) no longer fits the 16-bit register.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments