views:

281

answers:

2

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?

+1  A: 

You can divide your hexadecimal string into two-digit groups, and then use byte.parse to convert them to bytes. Use the NumberStyles.AllowHexSpecifier for that, for example:

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

The following routine will convert a hex 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();
}
Konamiman
+2  A: 

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);
}
Thomas Levesque
Now do it for the opposite endian? :)
leppie
does he NEED to convert it to the opposite endian? Only do it if it's needed I say ;-)
Erik van Brakel
i needs to be incremented by 2, not 1 I think.
Can Erten