'ARMv7 Assembly How to Read value of each bit
If I have a register that holds a value, how do I read each bit separately and process it in a way to store whether the bit is a 0 or 1? My understanding is to read the first bit, shift right, read first bit, shift right, and repeat until empty. But I can't figure out how to read the bit. I understand shift is just LSR which is easy.
Solution 1:[1]
There are multiple ways to achieve this.
You can you a tst instruction:
tst r0, #4 @ set Z if bit 0x04 is clear in R0
You can shift the desired bit out of the register into the carry flag:
movs r0, r0, lsr #3 @ set C if bit 0x04 was set in R0
You can extract the desired bit into a register on its own:
ubfx r1, r0, #2, #1 @ set R1 to 1 if bit 0x04 is set in R0
If you want to do this in a loop to process each bit in sequence, using the C flag (which you can conditionally execute code on with the CS and CC condition codes) is probably the best choice. For example, to count the bits in R0 you can use code like this:
mov r1, #0 @ initialise counter to zero
loop: movs r0, r0, lsr #1 @ shift R0 to the right and set C to its LSB
addcs r1, r1, #1 @ increment R1 if C was set
bne loop @ loop until R0 is clear
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
