Search code examples
assemblyx86gnu-assembleratt

Assembly - extract specific bit


I want to extract 17th bit from my 32bit (int) value. Am I doing this right? I'm using AT&T syntax.

movl $0x11112222,%eax   
movb $0b01000000,%bl
andb %ah,%bl

I put 32bit number into 32 bit register. Now 17th bit is in ah register (as well as other 16-23 bits). Now as it is second bit in ah register, I created a "mask". Then I'm doing and operation. Am I thinking right about this?


Solution

  • The general idea could work, but you have the wrong constant and the wrong byte. Your mask should be 0b000000100000000000000000 (or more readably 0x20000) and you should use 32 bit masking because you can not access the byte with bits 16-23. You mistakenly stated those live in %ah, but that's wrong, as %ah has bits 8-15.

    Also, this operation will leave the bit in place. Depending on what exactly you want you can shift the whole eax right by 17 and then keep the least significant bit.