Converting long string of binary to hex c#

前端 未结 10 1109
無奈伤痛
無奈伤痛 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:58

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

提交回复
热议问题