5

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?

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use hexadecimal format in C#:

string Result;
foreach(byte b in data)
{
    Result += String.Format("{0:00X}", b);
}

2 Comments

Concatenating strings like this is not a good idea (it's slow and creates many intermediate strings, which wastes memory and causes GC pressure), you should use StringBuilder or some other method.
Thanks, although that string format isn't correct. I think you mean "{0:X2}". Possibly better to use result += b.ToString("X2");, and yeah maybe better to use a StringBuilder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.