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:Or you could use LINQ and
string.Concat(). The .Net 4 version:In .Net 3.5, you have to add
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
StringBuilderand add the formatted bytes manually to it.