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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With