Is there a C # equivalent for Python unhexlify?

Possible duplicate:
How to convert hex to byte array?

I'm looking for a python compatible method in C # to convert hex to binary. I changed the hash to Python by doing the following:

import sha
import base64
import binascii

hexvalue = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
binaryval = binascii.unhexlify(hexvalue)
print base64.standard_b64encode(binaryval)
>> W6ph5Mm5Pz8GgiULbPgzG37mj9g=

      

So far, all the various C # Hex2Binary methods I have found ended up throwing OverflowExceptions:

static string Hex2Binary(string hexvalue)
{
    string binaryval = "";
    long b = Convert.ToInt64(hexvalue, 16);
    binaryval = Convert.ToString(b);
    byte[] bytes = Encoding.UTF8.GetBytes(binaryval);
    return Convert.ToBase64String(bytes);
}

      

Anyone got a hint on how to create a C # method to match the python output?

+2


source to share


2 answers


This value is too large for long (64 bits), so you get an OverflowException.

But it is very easy to convert hex to binary byte by byte (well, nibble in chunk actually):

static string Hex2Binary(string hexvalue)
{
    StringBuilder binaryval = new StringBuilder();
    for(int i=0; i < hexvalue.Length; i++)
    {
        string byteString = hexvalue.Substring(i, 1);
        byte b = Convert.ToByte(byteString, 16);
        binaryval.Append(Convert.ToString(b, 2).PadLeft(4, '0'));
    }
    return binaryval.ToString();
}

      



EDIT: The method above is converted to binary, not base64. It converts to base64:

static string Hex2Base64(string hexvalue)
{
    if (hexvalue.Length % 2 != 0)
        hexvalue = "0" + hexvalue;
    int len = hexvalue.Length / 2;
    byte[] bytes = new byte[len];
    for(int i = 0; i < len; i++)
    {
        string byteString = hexvalue.Substring(2 * i, 2);
        bytes[i] = Convert.ToByte(byteString, 16);
    }
    return Convert.ToBase64String(bytes);
}

      

+3


source


You can split a hex string into two groups and then use byte.parse to convert them to bytes. Use NumberStyles.AllowHexSpecifier for this, for example:

byte.Parse("3F", NumberStyles.AllowHexSpecifier);

      



The following procedure converts a hexadecimal string to a byte array:

private byte[] Hex2Binary(string hex)
{
    var chars = hex.ToCharArray();
    var bytes = new List<byte>();
    for(int index = 0; index < chars.Length; index += 2) {
        var chunk = new string(chars, index, 2);
        bytes.Add(byte.Parse(chunk, NumberStyles.AllowHexSpecifier));
    }
    return bytes.ToArray();
}

      

+1


source







All Articles