你可以這樣做:
DECLARE @inp VARCHAR(100) = '223-ABC-DEF-234'
, @BITS BIGINT;
SELECT @BITS =
CASE
WHEN CONVERT(BIGINT, LEFT(@inp, 3)) > 127
THEN (CONVERT(BIGINT, LEFT(@inp, 3))-128) * POWER(CONVERT(BIGINT, 2), 56)
-9223372036854775808
ELSE CONVERT(BIGINT, LEFT(@inp, 3)) * POWER(CONVERT(BIGINT, 2), 56)
END
+ CONVERT(BIGINT, ASCII(substring(@inp, 5, 1))) * POWER(CONVERT(BIGINT, 2), 48)
+ CONVERT(BIGINT, ASCII(substring(@inp, 6, 1))) * POWER(CONVERT(BIGINT, 2), 40)
+ CONVERT(BIGINT, ASCII(substring(@inp, 7, 1))) * POWER(CONVERT(BIGINT, 2), 32)
+ CONVERT(BIGINT, ASCII(substring(@inp, 9, 1))) * POWER(CONVERT(BIGINT, 2), 24)
+ CONVERT(BIGINT, ASCII(substring(@inp, 10, 1))) * POWER(CONVERT(BIGINT, 2), 16)
+ CONVERT(BIGINT, ASCII(substring(@inp, 11, 1))) * POWER(CONVERT(BIGINT, 2), 8)
+ CONVERT(BIGINT, RIGHT(@INP, 3));
select CONVERT(binary(8), @bits);
-- Returns 0xDF414243444546EA
SELECT CONVERT(VARCHAR, CONVERT(INT, 0XDF))
+ '-' + CHAR(0X41)
+ CHAR(0X42)
+ CHAR(0X43)
+ '-' + CHAR(0X44)
+ CHAR(0X45)
+ CHAR(0X46)
+ '-' + CONVERT(VARCHAR, CONVERT(INT, 0XEA));
-- Returns 223-ABC-DEF-234: our original string
大減法翻轉符號位。如果第一個數字大於127,則使用全部64位。由於BIGINT是帶符號的,因此乘以2^56將溢出數據類型。
這正是我需要做的。謝謝您的幫助! – Belizzle 2012-04-26 15:10:20