Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do bitwise exclusive OR in sql server between two binary types?

According this link: Bitwise Operators (Transact-SQL) we can do bitwise operation between binary and int, smallint, tinyint or vice versa.

But how can I make a bitwise exclusive OR in sql server between two binary types? Or if this is not possible how can I split a binary/varbinary to individual bytes?

The reason I'm asking for this is because I need to xor two numbers bigger than max int value. Thanks.

like image 286
tenkod Avatar asked Feb 03 '23 22:02

tenkod


2 Answers

All comments in code block

-- variables
declare @vb1 binary(16), @vb2 binary(16), @lo binary(8), @hi binary(8)

-- 2 guids to compare
declare @guid1 uniqueidentifier set @guid1 = '96B4316D-1EA7-4CA3-8D50-FEE8047C1329'
declare @guid2 uniqueidentifier set @guid2 = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'

-- split every 8 bytes into a binary(8), which is a bigint, the largest size usable with XOR
select @vb1 = @guid1, @vb2 = @guid2

-- xor the high and low parts separately
select @hi = convert(binary(8), substring(@vb1,1,8)) ^ convert(bigint, substring(@vb2,1,8))
select @lo = convert(binary(8), substring(@vb1,9,8)) ^ convert(bigint, substring(@vb2,9,8))

-- the final result, concatenating the bytes using char(8) - binary -> uniqueidentifier
select 'A', @guid1 union all
select 'B', @guid2 union all
select 'A XOR B = ', convert(uniqueidentifier, convert(binary(16),convert(char(8),@hi) + convert(char(8),@lo)))
like image 113
RichardTheKiwi Avatar answered Feb 05 '23 17:02

RichardTheKiwi


Per the Bitwise Exclusive OR documentation:

Note

Only one expression can be of either binary or varbinary data type in a bitwise operation.

like image 35
Joe Stefanelli Avatar answered Feb 05 '23 17:02

Joe Stefanelli