#83499 - 02/09/13 04:33 PM
XOR() - Exclusive OR operation using bitwise AND
|
Bonji
Starting to like KiXtart
Registered: 01/09/28
Posts: 148
Loc: Virginia
|
code:
;Function XOR() ; ;Author Ben Dulaney ; ;Version 1.0 ; ;Action Performs an eXclusive OR operation on a binary value ; ;Syntax XOR("Binary Value", "Bit to Swap") ; ;Parameters ; BINARY VALUE : REQUIRED. The value of the binary number to be manipulated. ; BIT TO SWAP : REQUIRED. A Power of 2 Number (i.e. 2,4,8,16,32,512) ; ;Returns Value of bit-swapped binary number ; 1 if BIT TO SWAP is invalid ; ;Dependencies KiX 4.10+ ; ;Example $VAL1 = XOR(577,64) ; ;Source
Function XOR($BinaryVal,$Bit) Dim $TstBit $TstBit = $Bit WHILE $TstBit MOD 2 = 0 AND $TstBit <> 1 $TstBit = $TstBit / 2 LOOP IF $TstBit <> 1 EXIT(1) RETURN ENDIF Dim $TmpVar $TmpVar=$BinaryVal - ($BinaryVal & $Bit) IF $TmpVar = $BinaryVal ;The bit was off $XOR = $BinaryVal + $Bit ELSE ;The bit was on $XOR = $BinaryVal - $Bit ENDIF EndFunction
[ 13. September 2002, 19:59: Message edited by: Ben Dulaney ]
|
|
Top
|
|
|
|
#83501 - 02/10/22 06:30 AM
Re: XOR() - Exclusive OR operation using bitwise AND
|
Paul Lemaire
Lurker
Registered: 01/12/06
Posts: 2
Loc: Milford, NH
|
This can be reduced to a one-liner. The following version works on machines that use twos-complement arithmetic (PCs). Instead of a single bit, you can supply a mask. Also, the arguments are interchangeable.
Function XOR($BinaryVal, $Mask)
$XOR = ($BinaryVal | $Mask) & (-1 - ($BinaryVal & $Mask))
EndFunction
_________________________
Paul Lemaire
Ace Consulting
Reality is stranger than fiction.
|
|
Top
|
|
|
|
#83502 - 02/10/30 06:12 AM
Re: XOR() - Exclusive OR operation using bitwise AND
|
Anonymous
Anonymous
Unregistered
|
|
|
Top
|
|
|
|
Moderator: Jochen, Radimus, Sealeopard, Bryce, Kdyer, Howard Bullock, Chris S., Glenn Barnas, Allen, Benny69, Mart
|
|