简体   繁体   English

在T-SQL中将负十进制转换为二进制

[英]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. 使用T-SQL,我想将负十进制转换为二进制并将其转换回。

Sample value: -9223372036854775543 样本值: -9223372036854775543

I try in convert with Calculater this value to Bin result is ... 1000000000000000000000000000000000000000000000000000000100001001 我尝试用Calculater将此值转换为Bin结果是... 1000000000000000000000000000000000000000000000000000000100001001

and Convert back to Dec. It's OK. 并转换回12月。可以。

How i can Convert like this with T-SQL(SQL2008) Script/Function ? 如何使用T-SQL(SQL2008)脚本/函数进行这样的转换? 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. 对于INT和BIGINT,可以使用CONVERT(VARCHAR(100),CAST(3 AS VARBINARY(100)),2)将十六进制表示形式作为字符串。 then you can do a simple search replace as every hex digit represents exactly 4 binary digits. 那么您可以进行简单的搜索替换,因为每个十六进制数字正好代表4个二进制数字。 However, with values outside of the BIGINT range there is no standard as to how they are represented internally. 但是,对于超出BIGINT范围的值,没有标准的内部表示方式。 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. 在数学中-3在二进制数中应为-11,而不是11111101。

To solve your problem you can either use a CLR function or you go through your number the old fashioned way: 要解决您的问题,您可以使用CLR函数,也可以通过老式的方式进行操作:

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). 要获得负数n的二进制补码,请计算1-n,然后使用上述算法将结果转换为二进制数,但要用相反的数字(0代替1,反之亦然)。 After flipping the digits into the right order prepend with enough 1s to fill your "box". 将数字翻转为正确的顺序后,请在前面加上足够的1,以填充“框”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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