你可以这样做:
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 位。仅乘以 2^56 就会溢出数据类型,因为 BIGINT 是有符号的。