Share via


Encode Hex String

I needed to get the hash as a string from a byte[].
I was snooping around X509Certificate class and saw a GetHashString method.
After a bit more digging i ended up at System.Security.Util.Hex this had the method i was looking for. Check out the EncodeHexString method.

public static String EncodeHexString(byte[] sArray)

{

String result = null;

if(sArray != null) {

char[] hexOrder = new char[sArray.Length * 2];

int digit;

for(int i = 0, j = 0; i < sArray.Length; i++) {

digit = (int)((sArray[i] & 0xf0) >> 4);

hexOrder[j++] = HexDigit(digit);

digit = (int)(sArray[i] & 0x0f);

hexOrder[j++] = HexDigit(digit);

}

result = new String(hexOrder);

}

return result;

}

      

      // converts number to hex digit. Does not do any range checks.

        static char HexDigit(int num) {

            return (char)((num < 10) ? (num + '0') : (num + ('A' - 10)));

        }