SQL:将整数转换为十六进制字符串? [英] SQL: Convert an integer into a hex string?
问题描述
如何将整数转换为十六进制字符串?我想将int转换为可以用作页面颜色的格式,例如'#ff0000'.
How do you convert an integer into a string of hex? I want to convert the int into a format that I can use as a color on my page for example '#ff0000'.
例如:
--This converts my int to hex:
CONVERT(VARBINARY(8), Color) Color,
我想做这样的事情:
'#' + CONVERT(NVARCHAR(10), CONVERT(VARBINARY(8), Color)) Color
但是转换varbinary字符串只是将其转换为ascii字符,而不是返回实际的十六进制字符串
But converting a varbinary string just converts it to an ascii character rather than returning the actual hex string
推荐答案
有一个内置函数可以从二进制值生成十六进制 strings
There is a built in function to generate hex strings from binary values
SELECT
'#' + sys.fn_varbintohexstr(CONVERT(BINARY(3), 0)),
'#' + sys.fn_varbintohexstr(CONVERT(BINARY(3), 255))
您需要 binary(3)
以确保输出字符串的正确长度
这是错误的.您得到4个十六进制数字,因为这里的0和255是4个字节的 int
值
You need binary(3)
to ensure the correct length of the output string
This is wrong. You get 4 hex digits because 0 and 255 here are 4 byte int
values
SELECT
'#' + sys.fn_varbintohexstr(CONVERT(varBINARY(8), 0)),
'#' + sys.fn_varbintohexstr(CONVERT(varBINARY(8), 255))
2017年10月更新:
Oct 2017 Update:
转换现在已内置到SQL Server中(自2008年开始!!),因此我们可以简单地使用CONVERT
The conversion is now built-in to SQL Server (since 2008!!) so we can simply use CONVERT
SELECT '#' + CONVERT(char(6), CONVERT(BINARY(3), 2570841), 2)
这篇关于SQL:将整数转换为十六进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!