Hex representations for byte arrays and ints

"4A 4F 55 4E 49 20 48 45 49 4B 4E 49 45 4D 49"? Today, among other things, I wrote a C# method that converts byte arrays to their hex representations. That's very simple actually – ToString does most of the grunt work, but some parameterizations help in customizing things.

public static string ToHexString(
byte[] bytes, bool spacesBetweenBytes, bool upperCase) {
StringBuilder sb =
new StringBuilder(bytes.Length*(spacesBetweenBytes ? 3 : 2));
string byteFormat =
"{0:" + (upperCase ? 'X' : 'x') + "2}" + (spacesBetweenBytes ? " " : "");
foreach (Byte b in bytes)
sb.AppendFormat(byteFormat, b);
// Cut off the last space if we were using spacesBetweenBytes
if (spacesBetweenBytes && bytes.Length > 0)
sb.Length--;
return sb.ToString();
}

If the bytes parameter is an array of bytes 123 and 234, the hex representations by the combinations of the two boolean params are as follows:

ToHexString
w/ {123, 234}
spacesBetweenBytes
false
spacesBetweenBytes
true
upperCase false 7bea 7b ea
upperCase true 7BEA 7B EA

I believe you have no trouble guessing what this overload does:

public static string ToHexString(int num, bool spacesBetweenBytes, bool upperCase) {
return ToHexString(
BitConverter.GetBytes(num),
spacesBetweenBytes,
upperCase
);
}

Update 2004-11-21 9:00 UTC+2: I made the int version use BitConverter instead of implicitly setting the byte order (endianness). Sorry about the edit; I must've been asleep when writing the entry.

November 20, 2004 · Jouni Heikniemi · 2 Comments
Posted in: .NET

2 Responses

  1. clinic - November 4, 2016

    I believe this is one of the so much vital information for me.

    And i'm happy studying your article. But wanna commentary on some basic
    issues, The web site taste is great, the articles is really great :
    D. Good task, cheers

  2. Micropigmentación en Murcia labios - November 19, 2016

    Excellent pieces. Keep posting such kind of information on your site.
    Im really impressed by it.
    Hello there, You have performed an excellent job.
    I'll definitely digg it and personally recommend to my friends.
    I'm confident they will be benefited from this web site.

Leave a Reply