Converting long string of binary to hex c#

前端 未结 10 1086
無奈伤痛
無奈伤痛 2020-11-29 11:25

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

the binary string looks something like this \"01100110100101110010011101010111001101

10条回答
  •  Happy的楠姐
    2020-11-29 11:51

    If you want to iterate over the hexadecimal representation of each byte in the string, you could use the following extension. I've combined Mitch's answer with this.

    static class StringExtensions
    {
        public static IEnumerable 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));
            }
        }
    }
    

    Example:

    string test = "0110011010010111001001110101011100110100001101101000011001010110001101101011";
    
    foreach (var hexVal in test.ToHex())
    {
        Console.WriteLine(hexVal);  
    }
    

    Prints

    06
    69
    72
    75
    73
    43
    68
    65
    63
    6B
    

提交回复
热议问题