Assembly Language for Beginners

(Jeff_L) #1

1.22. MANIPULATING SPECIFIC BIT(S)


Listing 1.298: Optimizing GCC 4.4.5 (IDA)

f:
; $a0=a
; rt variable will reside in $v0:
move $v0, $zero
; i variable will reside in $v1:
move $v1, $zero
li $t0, 1
li $a3, 32
sllv $a1, $t0, $v1
; $a1 = $t0<<$v1 = 1<<i


loc_14:
and $a1, $a0
; $a1 = a&(1<<i)
; increment i:
addiu $v1, 1
; jump to loc_28 if a&(1<<i)==0 and increment rt:
beqz $a1, loc_28
addiu $a2, $v0, 1
; if BEQZ was not triggered, save updated rt into $v0:
move $v0, $a2


loc_28:
; if i!=32, jump to loc_14 and also prepare next shifted value:
bne $v1, $a3, loc_14
sllv $a1, $t0, $v1
; return
jr $ra
or $at, $zero ; branch delay slot, NOP


1.22.6 Conclusion.


Analogous to the C/C++ shifting operators≪and≫, the shift instructions in x86 areSHR/SHL(for unsigned
values) andSAR/SHL(for signed values).


The shift instructions in ARM areLSR/LSL(for unsigned values) andASR/LSL(for signed values).


It’s also possible to add shift suffix to some instructions (which are called “data processing instructions”).


Check for specific bit (known at compile stage)


Test if the 0b1000000 bit (0x40) is present in the register’s value:


Listing 1.299: C/C++

if (input&0x40)
...


Listing 1.300: x86

TEST REG, 40h
JNZ is_set
; bit is not set


Listing 1.301: x86

TEST REG, 40h
JZ is_cleared
; bit is set


Listing 1.302: ARM (ARM mode)

TST REG, #0x40
BNE is_set
; bit is not set


Sometimes,ANDis used instead ofTEST, but the flags that are set are the same.

Free download pdf