c# – 如何使用.NET将byte []转换为字符串,以生成与SQL Server转换格式1或2相同的字符串?

SQL Server convert()函数可以将varbinary数据转换为具有此编码的字符串:Each binary character is converted into two hexadecimal characters. Ifthe length of the converted expression is greater than the da...

SQL Server convert()函数可以将varbinary数据转换为具有此编码的字符串:

Each binary character is converted into two hexadecimal characters. If
the length of the converted expression is greater than the data_type
length it will be right truncated.

If the data_type is a fix sized character type and the length of the
converted result is less than its length of the data_type; spaces are
added to the right of the converted expression to maintain an even
number of hexadecimal digits.

The characters 0x will be added to the left of the converted result
for style 1.

例如,输出可能看起来像’0x389D7156C27AA70F15DD3105484A8461A2268284′.我怎样才能在C#中轻松做同样的事情?即使用相同类型的编码将byte []转换为字符串?

解决方法:

您可以使用BitConverter.ToString()并删除它用作分隔符的连字符:

"0x" + BitConverter.ToString(bytes).Replace("-", "")

或者您可以使用LINQ和string.Concat().Net 4版本:

"0x" + string.Concat(bytes.Select(b => b.ToString("X2")))

在.Net 3.5中,您必须添加ToArray():

"0x" + string.Concat(bytes.Select(b => b.ToString("X2")).ToArray())

这不遵循关于截断和添加空格的规范,但我不确定您是否需要它.并且应该很容易修改代码来做到这一点.

这两个版本都是可读性和性能第二.如果您需要非常快,可以使用StringBuilder并手动添加格式化的字节.

本文标题为:c# – 如何使用.NET将byte []转换为字符串,以生成与SQL Server转换格式1或2相同的字符串?

基础教程推荐