本文介紹了轉(zhuǎn)換十進(jìn)制 <-->二進(jìn)制與 T-SQL的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
如何使用 T-SQL 將二進(jìn)制(基數(shù) 2 存儲(chǔ)為 varchar)轉(zhuǎn)換為十進(jìn)制(基數(shù) 10 存儲(chǔ)為 int 或 bigint),反之亦然?
How can I convert binary (base 2 stored as varchar) into decimal (base 10 stored as int or bigint) and the other way around, using T-SQL?
示例結(jié)果:
7
(dec) <-->111
(bin)136
(dec) <-->10001000
(bin)2123942362
(dec) <-->1111110100110001100100111011010
(bin)
7
(dec) <-->111
(bin)136
(dec) <-->10001000
(bin)2123942362
(dec) <-->1111110100110001100100111011010
(bin)
推薦答案
這個(gè)答案可以處理 bigint
This answer can handle bigint
轉(zhuǎn)換為位(包含 1 和 0 的 varchar)
Convert to bit(varchar containing 1 and 0)
DECLARE @input BIGINT = 9223372036854775807
;WITH N(N)AS
(
SELECT top 63
POWER(cast(2 as bigint),
ROW_NUMBER()over(ORDER BY (SELECT 1))-1)
FROM
(VALUES(1),(1),(1),(1))M(a),
(VALUES(1),(1),(1),(1))L(a),
(VALUES(1),(1),(1),(1))K(a)
)
SELECT
COALESCE
(
REVERSE
(
(
SELECT CAST(@input/N%2 as CHAR(1))
FROM N
WHERE N <= @input
for xml path(''), type
).value('.', 'varchar(max)')
)
, '0'
)
結(jié)果:
111111111111111111111111111111111111111111111111111111111111111
將包含位值的 varchar 轉(zhuǎn)換為 bigint
Convert varchar containing bit values to bigint
DECLARE @input varchar(max) =
'111111111111111111111111111111111111111111111111111111111111111'
;WITH N(V) AS
(
SELECT
ROW_NUMBER()over(ORDER BY (SELECT 1))
FROM
(VALUES(1),(1),(1),(1))M(a),
(VALUES(1),(1),(1),(1))L(a),
(VALUES(1),(1),(1),(1))K(a)
)
SELECT SUM(SUBSTRING(REVERSE(@input),V,1)*POWER(CAST(2 as BIGINT), V-1))
FROM N
WHERE V <= LEN(@input)
結(jié)果:
9223372036854775807
這篇關(guān)于轉(zhuǎn)換十進(jìn)制 <-->二進(jìn)制與 T-SQL的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!