Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting long string of binary to hex c#

Tags:

c#

hex

binary

I'm looking for a way to convert a long string of binary to a hex string.

the binary string looks something like this "0110011010010111001001110101011100110100001101101000011001010110001101101011"

I've tried using

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

but that only works if the binary string fits into a Uint64 which if the string is long enough it won't.

is there another way to convert a string of binary into hex?

Thanks

like image 679
Midimatt Avatar asked Apr 10 '11 14:04

Midimatt


People also ask

How do you convert binary to hexadecimal with examples?

Example − Convert binary number 1101010 into hexadecimal number. First convert this into decimal number: = (1101010)2 = 1x26+1x25+0x24+1x23+0x22+1x21+0x20 = 64+32+0+8+0+2+0 = (106)10 Then, convert it into hexadecimal number = (106)10 = 6x161+10x160 = (6A)16 which is answer.

How do I convert a char to hex then store it to a variable in C?

char c[2]="6A" char *p; int x = atoi(c);//atoi is deprecated int y = strtod(c,&p);//Returns only first digit,rest it considers as string and //returns 0 if first character is non digit char. By using val=strtol(string, NULL, 16); It returns a long type so you might need to check/cast it.


1 Answers

I just knocked this up. Maybe you can use as a starting point...

public static string BinaryStringToHexString(string binary)
{
    if (string.IsNullOrEmpty(binary))
        return binary;

    StringBuilder result = new StringBuilder(binary.Length / 8 + 1);

    // TODO: check all 1's or 0's... 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();
}
like image 109
Mitch Wheat Avatar answered Sep 28 '22 10:09

Mitch Wheat