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相同的字符串?


基础教程推荐
- C# 迭代器分部类与索引器详情 2023-06-21
- C# 8.0新特性介绍 2022-11-22
- C#实现汽车租赁系统项目 2023-01-11
- Winform 控件优化LayeredWindow无锯齿圆角窗体 2023-07-04
- c# 进程内部的同步 2023-03-14
- c#动态执行脚本的3种方式详解 2023-07-18
- C#9新特性之增强的模式匹配 2023-03-28
- C#基于QRCode实现动态生成自定义二维码图片功能示例 2023-01-11
- WPF如何自定义ProgressBar滚动条样式 2023-01-22
- Unity实现物体弧线运动到规定的坐标 2023-03-03