Search code examples
assemblyx86bitwise-operatorsmasking

using bit-wise operation to invert only the MSB of a binary number


I'm trying to figure out a best way to invert only MSB of a binary number and leaving other bits unchanged, given that the MSB is set.

for example if a binary number is 1111

I tried to and only the first half of ax which is ah, with 00b

and ah, 00b

which i get 0011, as you can see the bit next to MSB also changes when i did that

how should I change only the most significant bit without changing other bits?

thank in advance


Solution

  • First of all, your AND doesn't really invert any bits; it clears them.

    If you want to invert the most significant bit of AX you can do this:

    XOR AX,8000h
    

    or for the most significant nibble:

    XOR AX,0F000h
    

    or the most significant byte:

    XOR AX,0FF00h
    

    and so on.