Converting long string of binary to hex c#

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

    Considering four bits can be expressed by one hex value, you can simply go by groups of four and convert them seperately, the value won't change that way.

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

提交回复
热议问题