Why does the binary conversion of SQL Server not return a binary value?

Asked

Viewed 147 times

3

Why when I use the following command in SQL Server 2005

select convert(varbinary(16),N'123')

returns 0x310032003300 and not 1111011 that would be the binary value?

1 answer

6

@dellasavia, 1111011 is only 1 byte, in case an N'123' is a 3 character nvarchar.

Each character of an nvarchar occupies 2 bytes, totaling 6 bytes.

0x310032003300 can be read as follows in HEX:

HEX: 31 00 32 00 33 00

Binario in this case would be something like:

Binary: 00110001 00000000 00110010 00000000 00110011 00000000

however if instead of using an nvarchar, we did the conversion of a tinyint, then you would achieve the expected result.

DECLARE @valor as tinyint
SET @valor = 123
SELECT convert(binary(1), @valor)

But in this case, you would see an output 0x7B (HEX), which is the same as 01111011 (Binary).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.