Blitz3D+ Command Reference

expression1 Xor expression2

Parameters

expression1 - the value or condition on the left

expression2 - the value or condition on the right

Description

Combines two values bit by bit, keeping the bits that are set in one side but not the other.

Xor means "exclusive or": true when the two differ, false when they agree. As a condition that reads as "one or the other, but not both".

Its bit-level behaviour is the more useful half. Xor toggles: flags = flags Xor 4 flips bit 2 on if it was off and off if it was on, which is a neat one-liner for a pause key, a mute button or any switch that has no separate "set" and "clear" path. Xor also undoes itself - (a Xor k) Xor k gives back a - which is why it turns up in simple save-file obfuscation and in swap tricks. It is not encryption in any serious sense, but it is enough to stop a player editing their score with a text editor.

Xor shares the lowest precedence level with And and Or, and like them it is bitwise rather than logical, so give it comparisons or known 0/1 values when you are using it as a condition.

If you want to flip every bit of a value, the unary complement operator ~ does that in one step.

See also: And, Or, Not, Bin.

Example

; Xor Example
; -----------

; Xor is true when its two sides DIFFER. Bitwise, a bit comes out set
; when exactly one of the inputs has it.

a=%1100
b=%1010
Print "a       = "+Bin$(a)+" ("+a+")"
Print "b       = "+Bin$(b)+" ("+b+")"
Print "a Xor b = "+Bin$(a Xor b)+" ("+(a Xor b)+")"

Print ""

; Xor's party trick: applying the same mask twice restores the
; original - the classic lightweight scramble
message=12345
mask=54321
scrambled=message Xor mask
Print "message              = "+message
Print "message Xor mask     = "+scrambled+"  (scrambled)"
Print "scrambled Xor mask   = "+(scrambled Xor mask)+"  (the original is back)"

Print ""

; Xor 1 flips a true/false flag each time it runs - a one-line toggle
sound_on=True
sound_on=sound_on Xor 1
Print "Toggle once : sound_on = "+sound_on
sound_on=sound_on Xor 1
Print "Toggle again: sound_on = "+sound_on

Print ""
Print "Press any key to close the example"
WaitKey

End

Index