web-dev-qa-db-fra.com

Conversion de chaîne longue de binaire en hexa c #

Je cherche un moyen de convertir une longue chaîne de binaire en chaîne hexagonale.

la chaîne binaire ressemble à ceci "0110011010010111001001110101011100110100001101101000011001010110001101101011"

J'ai essayé d'utiliser 

hex = String.Format("{0:X2}", Convert.ToUInt64(hex, 2));

mais cela ne fonctionne que si la chaîne binaire s'inscrit dans un Uint64 qui ne le sera pas si la chaîne est assez longue.

existe-t-il un autre moyen de convertir une chaîne binaire en hexadécimal?

Merci

14
Midimatt

Je viens de casser ça. Peut-être que vous pouvez utiliser comme point de départ ...

public static string BinaryStringToHexString(string binary)
{
    StringBuilder result = new StringBuilder(binary.Length / 8 + 1);

    // TODO: check all 1's or 0's... Will throw otherwise

    int mod4Len = binary.Length % 8;
    if (mod4Len != 0)
    {
        // pad to length multiple of 8
        binary = binary.PadLeft(((binary.Length / 8) + 1) * 8, '0');
    }

    for (int i = 0; i < binary.Length; i += 8)
    {
        string eightBits = binary.Substring(i, 8);
        result.AppendFormat("{0:X2}", Convert.ToByte(eightBits, 2));
    }

    return result.ToString();
}
25
Mitch Wheat

Cela pourrait vous aider:

string HexConverted(string strBinary)
    {
        string strHex = Convert.ToInt32(strBinary,2).ToString("X");
        return strHex;
    }
11
Pranav Labhe
Convert.ToInt32("1011", 2).ToString("X");

Pour une chaîne plus longue que cela, vous pouvez simplement la diviser en plusieurs octets:

var binary = "0110011010010111001001110101011100110100001101101000011001010110001101101011";
var hex = string.Join(" ", 
            Enumerable.Range(0, binary.Length / 8)
            .Select(i => Convert.ToByte(binary.Substring(i * 8, 8), 2).ToString("X2")));
5
Soroush Falahati

Je suis venu avec cette méthode. Je suis nouveau dans la programmation et le C # mais j'espère que vous l'apprécierez:

static string BinToHex(string bin)
{
    StringBuilder binary = new StringBuilder(bin);
    bool isNegative = false;
    if (binary[0] == '-')
    {
        isNegative = true;
        binary.Remove(0, 1);
    }

    for (int i = 0, length = binary.Length; i < (4 - length % 4) % 4; i++) //padding leading zeros
    {
        binary.Insert(0, '0');
    }

    StringBuilder hexadecimal = new StringBuilder();
    StringBuilder Word = new StringBuilder("0000");
    for (int i = 0; i < binary.Length; i += 4)
    {
        for (int j = i; j < i + 4; j++)
        {
            Word[j % 4] = binary[j];
        }

        switch (Word.ToString())
        {
            case "0000": hexadecimal.Append('0'); break;
            case "0001": hexadecimal.Append('1'); break;
            case "0010": hexadecimal.Append('2'); break;
            case "0011": hexadecimal.Append('3'); break;
            case "0100": hexadecimal.Append('4'); break;
            case "0101": hexadecimal.Append('5'); break;
            case "0110": hexadecimal.Append('6'); break;
            case "0111": hexadecimal.Append('7'); break;
            case "1000": hexadecimal.Append('8'); break;
            case "1001": hexadecimal.Append('9'); break;
            case "1010": hexadecimal.Append('A'); break;
            case "1011": hexadecimal.Append('B'); break;
            case "1100": hexadecimal.Append('C'); break;
            case "1101": hexadecimal.Append('D'); break;
            case "1110": hexadecimal.Append('E'); break;
            case "1111": hexadecimal.Append('F'); break;
            default:
                return "Invalid number";
        }
    }

    if (isNegative)
    {
        hexadecimal.Insert(0, '-');
    }

    return hexadecimal.ToString();
}
3
Simeon Georgiev

Si vous utilisez .NET 4.0 ou version ultérieure et si vous souhaitez utiliser System.Numerics.dll (pour la classe BigInteger), la solution suivante fonctionne correctement:

public static string ConvertBigBinaryToHex(string bigBinary)
{
    BigInteger bigInt = BigInteger.Zero;
    int exponent = 0;

    for (int i = bigBinary.Length - 1; i >= 0; i--, exponent++)
    {
        if (bigBinary[i] == '1')
            bigInt += BigInteger.Pow(2, exponent);
    }

    return bigInt.ToString("X");
}
1
Marcos Arruda

Considérant que quatre bits peuvent être exprimés par une valeur hexadécimale, vous pouvez simplement aller par groupes de quatre et les convertir séparément, la valeur ne changera pas de cette façon. 

string bin = "11110110";

int rest = bin.Length % 4;
if(rest != 0)
    bin = new string('0', 4-rest) + bin; //pad the length out to by divideable by 4

string output = "";

for(int i = 0; i <= bin.Length - 4; i +=4)
{
    output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}
1
Femaref

Si vous souhaitez effectuer une itération sur la représentation hexadécimale de chaque octet de la chaîne, vous pouvez utiliser l'extension suivante. J'ai combiné la réponse de Mitch avec this .

static class StringExtensions
{
    public static IEnumerable<string> ToHex(this String s) {
        if (s == null)
            throw new ArgumentNullException("s");

        int mod4Len = s.Length % 8;
        if (mod4Len != 0)
        {
            // pad to length multiple of 8
            s = s.PadLeft(((s.Length / 8) + 1) * 8, '0');
        }

        int numBitsInByte = 8;
        for (var i = 0; i < s.Length; i += numBitsInByte)
        {
            string eightBits = s.Substring(i, numBitsInByte);
            yield return string.Format("{0:X2}", Convert.ToByte(eightBits, 2));
        }
    }
}

Exemple:

string test = "0110011010010111001001110101011100110100001101101000011001010110001101101011";

foreach (var hexVal in test.ToHex())
{
    Console.WriteLine(hexVal);  
}

Impressions

06
69
72
75
73
43
68
65
63
6B
0
Alex Chrostowski
static string BinToHex(string bin)
{
    if (bin == null)
        throw new ArgumentNullException("bin");
    if (bin.Length % 8 != 0)
        throw new ArgumentException("The length must be a multiple of 8", "bin");

    var hex = Enumerable.Range(0, bin.Length / 8)
                     .Select(i => bin.Substring(8 * i, 8))
                     .Select(s => Convert.ToByte(s, 2))
                     .Select(b => b.ToString("x2"));
    return String.Join(null, hex);
}
0
Thomas Levesque

Considérant que quatre bits peuvent être exprimés par une valeur hexadécimale, vous pouvez simplement aller par groupes de quatre et les convertir séparément, la valeur ne changera pas de cette façon. 

string bin = "11110110";

int rest = bin.Length % 4;
bin = bin.PadLeft(rest, '0'); //pad the length out to by divideable by 4

string output = "";

for(int i = 0; i <= bin.Length - 4; i +=4)
{
    output += string.Format("{0:X}", Convert.ToByte(bin.Substring(i, 4), 2));
}
0
Femaref