2009-09-22 6 views
2

Possible en double:
How to convert hex to a byte array?Existe-t-il un C# équivalent à unhexlify de Python?

Je cherche une méthode python compatible en C# pour convertir hexadécimal en binaire. J'ai renversé un hachage en Python en faisant ceci:

import sha 
import base64 
import binascii 

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

Jusqu'à présent, toutes les différentes Hex2Binary méthodes C# J'ai trouvé finissent par jeter 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); 
} 

Quelqu'un a une astuce sur la façon dont produire une méthode C# pour correspondre à la sortie de python?

+0

en double de http://stackoverflow.com/questions/854012/how-to-convert-hex-to-a-byte-array –

+0

(utilisation Convert.ToBase64String avec le résultat byte array, btw.) –

+0

Ce n'est pas un IMO en double, c'est spécifique à la compatibilité entre Python et C#. La réponse peut être la même, mais la question (sur laquelle les autres peuvent tomber) est certainement différente. – RyanW

Répondre

3

Cette valeur est trop grande pour une longue (64bits), C'est pourquoi vous obtenez une exception OverflowException.

Mais il est très facile de convertir hex à l'octet par octet binaire (bien, grignotage par grignotage fait):

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: la méthode ci-dessus convertit en binaire, pas base64. Celui-ci se transforme en 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); 
} 
+0

Maintenant le faire pour l'autre boutiste? :) – leppie

+0

at-il besoin de le convertir en l'autre boutiste? Seulement le faire si c'est nécessaire je dis ;-) –

+0

je dois être incrémenté de 2, pas 1 je pense. – Codingday

1

Vous pouvez diviser votre chaîne hexadécimale en groupes à deux chiffres, puis utiliser byte.parse pour les convertir en octets. Utilisez le NumberStyles.AllowHexSpecifier pour que, par exemple:

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

La routine suivante convertit une chaîne hexagonale à un tableau d'octets:

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(); 
}