Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from integer to binary and back in SQL Server

I've been banging my head against the wall with this one all morning.

The following SQL code and its' result makes no sense to me:

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

which results in:

-1060082528

What? Why doesn't the result equal my original integer?

My whole objective is to convert an integer into bytes and store those bytes into the database, but without getting this basic example to work I am stuck. Can anyone explain what I'm doing wrong?

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

like image 771
Slider345 Avatar asked Sep 14 '11 19:09

Slider345


People also ask

How do I convert int to numeric in SQL?

Use the CAST() function to convert an integer to a DECIMAL data type. This function takes an expression or a column name as the argument, followed by the keyword AS and the new data type. In our example, we converted an integer (12) to a decimal value (12.00).

What is CAST () and convert () functions in SQL Server?

The T-SQL language offers two functions to convert data from one data type to a target data type: CAST and CONVERT. In many ways, they both do the exact same thing in a SELECT statement or stored procedure, but the SQL Server CONVERT function has an extra parameter to express style.

What does convert () do in SQL?

The CONVERT() function converts a value (of any type) into a specified datatype.

What is To_number in SQL Server?

TO_NUMBER converts a string to a number of data type NUMERIC. TO_CHAR performs the reverse operation; it converts a number to a string. CAST and CONVERT can be used to convert a string to a number of any data type. For example, you can convert a string to a number of data type INTEGER.


2 Answers

As I noted in my earlier comment, 2,691,485,888 is larger than what an INT can hold.

This will work:

select CONVERT(BIGINT, CONVERT(BINARY(30), CONVERT(BIGINT, 2691485888)))
like image 160
Joe Stefanelli Avatar answered Oct 21 '22 05:10

Joe Stefanelli


The value 2691485888 cannot be held in an INT - it is too large:

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

There is a good chance you are seeing the result of an overflow.

A data type that can handle that value is BIGINT.

like image 4
Oded Avatar answered Oct 21 '22 05:10

Oded