DarioSantarelli.Blog(this);

[C#] Byte Array to Hex string

Posted by dariosantarelli on October 16, 2010

There are a lot of ways of converting a byte array to the corresponding hexadecimal string. I usually adopt the BitConverter class in order to optimize the readibility of code, but starting from the .NET Framework 3.0 the same task can be obtained using a single line of code through extensions methods:

[TestMethod]
public void BitConverterVsStringConcatAndExtensionMethod()
{
 
byte[] bytes = new byte[] { 0x00,0xAA,0xB0,0xC8,0x99,0x11,0x01,0x02 … };
 
string expectedResult = "00AAB0C899110102…";
 
 
string result1 = BitConverter.ToString(bytes).Replace("-",string.Empty);
 
 
string result2 = string.Concat(bytes.Select(b => b.ToString("X2")));

 
Assert.AreEqual(expectedResult, result1);
 
Assert.AreEqual(expectedResult, result2);
}

OK no performance issue has been discussed. Aren’t you satisfied? Follow this thread !!! (4 years of discussion :D)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: