Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert byte[] to a string using .NET to produce same string as SQL Server Convert format 1 or 2?

The SQL Server convert() function can convert varbinary data to a string with this encoding:

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.

For example, output might look like '0x389D7156C27AA70F15DD3105484A8461A2268284'. How can I easily do the same thing in C#? i.e. convert a byte[] to a string using the same sort of encoding?

like image 434
Rory Avatar asked Oct 29 '11 16:10

Rory


1 Answers

You can use BitConverter.ToString() and drop the hyphens it uses as a separator:

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

Or you could use LINQ and string.Concat(). The .Net 4 version:

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

In .Net 3.5, you have to add ToArray():

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

This doesn't follow the specification you have with regards to truncating and adding spaces, but I'm not sure you need that. And it should be easy to modify the code to do that.

Both of these versions go for readability first and performance second. If you need this to be very fast, you could use StringBuilder and add the formatted bytes manually to it.

like image 173
svick Avatar answered Nov 15 '22 03:11

svick