Topic
  • 1 reply
  • Latest Post - ‏2005-05-24T06:54:33Z by SystemAdmin
SystemAdmin
SystemAdmin
232 Posts

Pinned topic the practicality of xor

‏2004-07-29T22:28:06Z |
please forgive me, i think i may be posting this in the wrong forum, but...my friend and i were wondering where xor would be used. (we're working with assembly)

why is it used? or...if u were to compile something in c/cpp where would u see xor in the asm code?

please understand we know what xor does. but WHY use it?
Updated on 2005-05-24T06:54:33Z at 2005-05-24T06:54:33Z by SystemAdmin
  • SystemAdmin
    SystemAdmin
    232 Posts

    Re: the practicality of xor

    ‏2005-05-24T06:54:33Z  
    > please forgive me, i think i may be posting this in
    > the wrong forum, but...my friend and i were wondering
    > where xor would be used. (we're working with
    > assembly)

    Yes, this appears a bit off topic.

    > why is it used? or...if u were to compile something
    > in c/cpp where would u see xor in the asm code?
    >
    > please understand we know what xor does. but WHY use
    > it?

    Both logical and bitwise XOR are used quite often. A logical XOR could be used to check if only only one of two boolean variables are "true" e.g.

    if( cond1 && !cond2 || !cond1 && cond2 ) {
    // do stuff
    }

    Bitwise XOR is also used quite often. Sometimes if register space is really tight and you need to swap two variables, the compiler may opt to issue something like

    xor r1, r2 -> r2
    xor r1, r2 -> r1
    xor r1, r2 -> r2

    ...instead of

    mov r1 -> r3
    mov r2 -> r1
    mov r3 -> r2

    As a special case, on the x86 architecture, it turns out to be faster (and more memory efficient) for the compiler to output

    xor r1, r1 -> r1

    ...instead of

    movi 0 -> r1

    ...to clear a variable to 0.

    Apologies for the unconventional assembly syntax but I hope it is intuitive to understand.