This question already has an answer here:
How do I convert a byte[]
to a string
? Every time I attempt it, I get
System.Byte[]
instead of the value.
Also, how do I get the value in Hex instead of a decimal?
This question already has an answer here:
How do I convert a byte[]
to a string
? Every time I attempt it, I get
System.Byte[]
instead of the value.
Also, how do I get the value in Hex instead of a decimal?
There is a built in method for this:
Result: 01-02-04-08-10-20
If you want it without the dashes, just remove them:
Result: 010204081020
If you want a more compact representation, you can use Base64:
Result: AQIECBAg
I like using extension methods for conversions like this, even if they just wrap standard library methods. In the case of hexadecimal conversions, I use the following hand-tuned (i.e., fast) algorithms:
Very fast extension methods (with reversal):
Beats all the others in the speed test above:
As others have said it depends on the encoding of the values in the byte array. Despite this you need to be very careful with this sort of thing or you may try to convert bytes that are not handled by the chosen encoding.
Jon Skeet has a good article about encoding and unicode in .NET. Recommended reading.
Just to add one more answer to the pile, there is a
System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary
class that I've used which can convert bytes to and from hex:Not sure how it compares (benchmark) to other implementations, but IMO it is pretty simple -- especially for converting from hex back into bytes.
You combine LINQ with string methods: