简体   繁体   中英

Convert negative decimal to binary in T-SQL

I have tried to find information and how. But it did not contain any information that would help.

With T-SQL, I want to convert negative decimal to binary and convert it back.

Sample value: -9223372036854775543

I try in convert with Calculater this value to Bin result is ... 1000000000000000000000000000000000000000000000000000000100001001

and Convert back to Dec. It's OK.

How i can Convert like this with T-SQL(SQL2008) Script/Function ? Long time to find information for how to. Anyone who knows about this, please help.

There is no build in functionality. for INT and BIGINT you can use CONVERT(VARCHAR(100),CAST(3 AS VARBINARY(100)),2) to get the hex representation as a string. then you can do a simple search replace as every hex digit represents exactly 4 binary digits. However, with values outside of the BIGINT range there is no standard as to how they are represented internally. You might get the right result or not and that behavior might even change between versions.

There is also no standard as to how negative numbers are represented. Most implementations of integers use the two's-complement representation . In that representation the top most bit indicates the sign of the number. How many bits you have is a metter of convention and fully dependent on your environment.

In mathematics -3 woud be -11 in binary and not 11111101.

To solve your problem you can either use a CLR function or you go through your number the old fashioned way:

Is it odd? -> output a 1
Is it even? -> output a 0
integer divide by 2
repeat until the value is 0

This will give you the digits in opposite order, so you have to flip the result. To get the two's-complement representation of a negative number n calculate 1-n, convert the result to binary using the above algorithm but with reversed digits (0 instead of 1 and vice versa). After flipping the digits into the right order prepend with enough 1s to fill your "box".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM