phonemyatt -4 years ago 109
C# Question

# Why a byte is added 0x37 while true and 0x30 while false in this byte array to hex string conversion in C#?

I found this method to convert byte array to hex string on msdn forum. The code is working fine but I have problem understanding part of the code. Here is code to convert byte array to hex string.

``````private static string HexStr(byte[] p) {
char[] c = new char[p.Length * 2 + 2 ]; //reason for +2 is for 0x; can be removed

byte b;
c[0] = '0';c[1] = 'x';   //can be removed
for (int y = 0, x = 2; y < p.Length; ++y, ++x) // x = 0 if remove
{

b = ((byte)(p[y] >> 4));

c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30); ///Why 0x37 and 0x30?

b = ((byte)(p[y] & 0xF));

c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30);///Here too?

}

return new string(c);
}
``````

Why byte b is added 0x37 when b is greater than 9 and is added 0x30 otherwise? After quick google search, the only information I found is byte 0x37 = decimal 55 = char '0' and byte 0x30 = decimal 48 = char '0'. Can somebody explain to me?

Rewrite the expression as:

``````char ch = (char)(b > 9 ? b + 'A' - 10 : b + '0');
``````

and it will become clear!

'A' == 0x41, 'A' - 10 == 0x37, '0' == 0x30

If `b <= 9`, then `b + '0'` == the digit you need (note that I consider to be more "human readable" to write `'0' + b`... You start from the char `'0'` and you advance `b` places in the Unicode table), if `b >= 10`, then you have to select a letter A-F, adding `'A'` to your digit `b` but subtracting 10 (because `'A'` is "zero" in the range `A-F`... In human readable form it would be `'A' + (b - 10)`).

Note that there is another way to write the expression, normally easier (but totally different algorithm-wyse)

``````char ch = "0123456789ABCDEF"[b];
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download