Search code examples
assemblyx86gnu-assembler

Any equivalent function of ARM's ldrb in x86 gas syntax?


I'm looking to load a string byte by byte to check for a null value that signifies the termination of that string in x86. I had prior done this in ARM using ldrb as such:

loop:
    ldrb    r1, [r0], #1 //Load next byte of string into r0
    cmp     r1, #0 //Check this byte against 0
    beq     end //If the byte is equal stop and print
    //... Other operations omitted  
    b       loop//Branch back to top

In this example r0 holds the string and ldrb is used to load the next 1 byte into r1 per loop cycle. I'd be looking to do roughly the same thing in x86


Solution

  • Surely you have an instruction set reference. There is really no way around knowing the basic data movement and comparison instructions. You shouldn't rely on being spoon-fed.

    That said, the x86 counterpart to ldrb is called movzbl (move zero extended byte to long, called movzx in intel syntax). Here is a sample implementation using eax for r0 and edx for r1:

    loop:
        movzbl 1(%eax), %edx
        cmpl $0, %edx
        je end
        // ... other operations omitted
        jmp loop
    

    Also note that x86 is CISC and supports operating on memory directly, meaning you can compare a value in memory to 0 without loading into a register. You can use that if you don't need the value of the character.

    Furthermore, certain parts of x86 registers can be used directly, in this case you could write movb 1(%eax), %dl to use the low 8 bits of %edx. The top 24 bits then stay unchanged, so you should only use byte-sized comparison too.

    Speaking of the comparison, common idioms for zero testing include using and, or or test instructions with both operands being the register in question, such as test %edx, %edx. This is done because these produce shorter machine code.