Is there a C# equivalent to Python's unhexlify?

binary, c#, hex, python

Solution

This value is too big for a long (64bits), that's why you get an OverflowException.

But it's very easy to convert hex to binary byte by byte (well, nibble by nibble 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 converts to binary, not to base64. This one 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);
}

Problem

Possible Duplicate: How to convert hex to a byte array? I'm searching for a python compatible method in C# to convert hex to binary. I've reversed a hash in Python by doing this: ``` import sha import base64 import binascii hexvalue = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8" binaryval = binascii.unhexlify(hexvalue) print base64.standard_b64encode(binaryval) >> W6ph5Mm5Pz8GgiULbPgzG37mj9g= ``` So far all of the various Hex2Binary C# methods I've found end 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); } ``` Anybody got a tip on how to produce a C# method to match the python output?

Original source

Related problems