我使用MS SQL Server 2008:
我将'0x98120000'
转换为字符串'00011001010010000000000000000000'
。
如何转换逆转。
请帮帮我。感谢。
答案 0 :(得分:0)
declare @t binary(4)
set @t = 0x98120000
-- Out string : '00011001010010000000000000000000'
Select REVERSE(REPLICATE('0',8-DATALENGTH(dbo.DecimalToBinary(CONVERT(tinyint,0xFF) & SUBSTRING(@t,1,1))))+dbo.DecimalToBinary(CONVERT(tinyint,0xFF) & SUBSTRING(@t,1,1)))+''+
REVERSE(REPLICATE('0',8-DATALENGTH(dbo.DecimalToBinary(CONVERT(tinyint,0xFF) & SUBSTRING(@t,2,1))))+dbo.DecimalToBinary(CONVERT(tinyint,0xFF) & SUBSTRING(@t,2,1)))+''+
REVERSE(REPLICATE('0',8-DATALENGTH(dbo.DecimalToBinary(CONVERT(tinyint,0xFF) & SUBSTRING(@t,3,1))))+dbo.DecimalToBinary(CONVERT(tinyint,0xFF) & SUBSTRING(@t,3,1)))+''+
REVERSE(REPLICATE('0',8-DATALENGTH(dbo.DecimalToBinary(CONVERT(tinyint,0xFF) & SUBSTRING(@t,4,1))))+dbo.DecimalToBinary(CONVERT(tinyint,0xFF) & SUBSTRING(@t,4,1))) As [String]
--Out String binary : 0x98120000
Declare @String varchar(200)
Set @String='00011001010010000000000000000000'
Select Cast([dbo].[BinaryToDecimal](REVERSE(SUBSTRING(@String,1,8))) as binary(1))+
Cast([dbo].[BinaryToDecimal](REVERSE(SUBSTRING(@String,9,8))) as binary(1))+
Cast([dbo].[BinaryToDecimal](REVERSE(SUBSTRING(@String,17,8))) as binary(1))+
Cast([dbo].[BinaryToDecimal](REVERSE(SUBSTRING(@String,25,8))) as binary(1)) as [ChangeBinary]
*** FUNCTION [dbo]。[DecimalToBinary] ****
CREATE FUNCTION [dbo].[DecimalToBinary]
(
@Input bigint
)
RETURNS varchar(5000)
AS
BEGIN
DECLARE @Output varchar(5000) = ''
WHILE @Input > 0
BEGIN
SET @Output = @Output + CAST((@Input % 2) AS varchar)
SET @Input = @Input / 2
END
RETURN REVERSE(@Output)
END
***** FUNCTION [dbo]。[BinaryToDecimal] *****
CREATE FUNCTION [dbo].[BinaryToDecimal]
(
@Input varchar(255)
)
RETURNS bigint
AS
BEGIN
DECLARE @Cnt tinyint = 1
DECLARE @Len tinyint = LEN(@Input)
DECLARE @Output bigint = CAST(SUBSTRING(@Input, @Len, 1) AS bigint)
WHILE(@Cnt < @Len)
BEGIN
SET @Output = @Output + POWER(CAST(SUBSTRING(@Input, @Len - @Cnt, 1) * 2 AS bigint), @Cnt)
SET @Cnt = @Cnt + 1
END
RETURN @Output
END