Converting long string of binary to hex c#

前端 未结 10 1110
無奈伤痛
無奈伤痛 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条回答
  •  情话喂你
    2020-11-29 11:40

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

提交回复
热议问题