Converting from integer to binary and back to SQL Server

I banged my head against the wall this morning.

The following SQL code and its result do not make any sense to me:

select CONVERT(INT, CONVERT(BINARY(30),2691485888))

that leads to:

-1060082528

What? Why is the result not equal to my original whole?

My goal is to convert an integer to bytes and store those bytes in a database, but without this basic example working, I'm stuck. Can someone explain what I'm doing wrong?

By the way, I am using Sql Server 2005 (9.0.4340)

+5
source share
3 answers

As I noted in my previous comment, 2,691,485,888 are more than INT can hold.

This will work:

select CONVERT(BIGINT, CONVERT(BINARY(30), CONVERT(BIGINT, 2691485888)))
+7

2691485888 INT - :

int -2 ^ 31 (-2,147,483,648) 2 ^ 31-1 (2,147,483,647) 4

, .

, , - BIGINT.

+4

2691485888 is outside the upper limit of the integer data type (which is 2147483647)

If you convert it to bigint, this should result in the correct amount.

+1
source

All Articles