Converting long string of binary to hex c#

前端 未结 10 1090
無奈伤痛
無奈伤痛 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 12:01

    If you're using .NET 4.0 or later and if you're willing to use System.Numerics.dll (for BigInteger class), the following solution works fine:

    public static string ConvertBigBinaryToHex(string bigBinary)
    {
        BigInteger bigInt = BigInteger.Zero;
        int exponent = 0;
    
        for (int i = bigBinary.Length - 1; i >= 0; i--, exponent++)
        {
            if (bigBinary[i] == '1')
                bigInt += BigInteger.Pow(2, exponent);
        }
    
        return bigInt.ToString("X");
    }
    

提交回复
热议问题