C#中二进制字符串转BigInteger遇构造函数参数错误求解
解决C#二进制字符串转BigInteger的错误问题
你遇到的错误是因为**BigInteger没有接受字符串+进制参数的构造函数重载**,编译器找不到匹配的构造方法,只能尝试匹配其他重载(比如BigInteger(ReadOnlySpan<byte>, bool)),从而导致参数类型不兼容的报错。
以下是几种正确的实现方式:
方法一:使用BigInteger.Parse(.NET 6+适用)
通过指定NumberFormatInfo的NumberBase为2,直接解析二进制字符串:
using System.Numerics; using System.Globalization; string binaryStr = "100101000111111110000"; BigInteger bi = BigInteger.Parse(binaryStr, NumberStyles.Integer, new NumberFormatInfo { NumberBase = 2 });
方法二:位运算手动构建(全.NET版本兼容)
适合超长二进制字符串,兼容性最好:
using System.Numerics; string binaryStr = "100101000111111110000"; BigInteger bi = 0; foreach (char bit in binaryStr) { bi <<= 1; // 左移一位,等价于乘以2 if (bit == '1') { bi |= 1; // 将最低位设为1 } }
方法三:转字节数组构造(可控字节顺序场景)
如果需要手动控制字节顺序,可先将二进制字符串转为字节数组再构造BigInteger:
using System.Numerics; string binaryStr = "100101000111111110000"; // 补前导零,确保字符串长度是8的倍数 int padding = (8 - binaryStr.Length % 8) % 8; string paddedBinary = binaryStr.PadLeft(binaryStr.Length + padding, '0'); byte[] bytes = new byte[paddedBinary.Length / 8]; for (int i = 0; i < bytes.Length; i++) { string byteSegment = paddedBinary.Substring(i * 8, 8); bytes[i] = Convert.ToByte(byteSegment, 2); } // BigInteger构造函数默认用小端字节序,反转数组适配二进制字符串的大端顺序 Array.Reverse(bytes); // 若二进制最高位为1,会被解析为负数,补一个0字节确保为正数 if ((bytes[^1] & 0x80) != 0) { Array.Resize(ref bytes, bytes.Length + 1); bytes[^1] = 0; } BigInteger bi = new BigInteger(bytes);
内容的提问来源于stack exchange,提问作者UniqueHold
相关产品推荐
相关产品推荐

