srjt
srjt

Reputation: 316

Converting varchar to varbinary

Trying to understand varchar to varbinary conversion, when i run below query

select CAST(3 as varbinary(512))

result is 0x00000003 but if I cast 0x00000003 back to varchar using below query then result is ' '

cast(0x00000003 as varchar)

Below query actually gives me result as 3.

select cast(0x33 as varchar)

I tried it with Convert also, but results are same. I would appreciate if anyone can explain this behavior.

Upvotes: 0

Views: 3928

Answers (2)

Vamsi Prabhala
Vamsi Prabhala

Reputation: 49260

You should convert binary to int and then cast it as a varchar to get the same number back.

select cast(cast(CAST(3 as varbinary(512)) as int) as varchar)

Upvotes: 0

Martin Smith
Martin Smith

Reputation: 453278

3 is not a varchar. It is an int. So you see the binary format of a signed int stored in twos complement.

'3' is a varchar

select CAST('3' as varbinary(512))

Returns 0x33 (decimal 51 which is the ASCII code for 3)

Upvotes: 6

Related Questions