繁体   English   中英

java中的长二进制字符串算法

[英]Long binary string arithmetic in java

我正在做一个基于服务器的程序,我希望将2个二进制字符串相乘。 这些字符串很长,因此它们不能转换为longint类型。 其中一个字符串的示例是:

01100010 00110110 00110011 00110111 00110100 00111001 00111001 00111001 00110110 01100011 00110110 01100101 00111001 00110011 00110011 00110010 00110010 00110010 01100001 00110101 01100100 01100011 01100011 01100010 01100100 00111000 01100100 01100100 00110010 00110110 00110110 00110100 00111000 01100110 00110001 00110100 00110110 01100110 01100110 01100100 00110100 00110101 00110100 01100010 01100010 00111001 00111001 00110110 01100110 01100010 00111000 00110011 00110000 00110011 00110010 01100110 01100010 00110001 01100010 01100001 00110100 01100011 01100011 00111000 00110110 00110111 01100110 00110001 00111001 00110110 00110110 00110001 00110001 01100101 00110010 00111000 01100100 01100110 01100110 01100001 01100100 00110100 00110110 00110000 00110010 00111001 00111001 00110011 00111000 01100001 00111001 00110111 00110111 00110011 00110010 01100011 00110100 00110000 01100011 01100101 01100010 01100011 01100011 00110101 01100110 00110111 00110000 00110110 00110000 00110110 00110101 01100101 01100001 01100100 00110011 01100100 00110100 01100110 01100110 00110111 00110110 00110011 00110111 00110100 00111001 00111001 00111001 00110000 00110001 00111001 01100001 01100010 01100101 00110011 00110010 00111001 01100011 01100110 01100101 00110011 00110010 01100011 01100011 00110010 00111000 00110110 00110001 01100001 00110111 00110110 00110101 01100010

这个字符串可以有空格。 没关系。 我的问题是,如何用这个字符串乘以,假设,01100011? 乘数的长度是可变的,因此灵活性是必须的。

提前致谢!

只需使用BigInteger并指定基数:

BigInteger bigNumber = new BigInteger("101000101110...1010".replaceAll("\s+", ""), 2);

你会发现它支持像multiplyadd等算术运算。例如,在创建上面的变量之后,我们可以说:

BigInteger bigProduct = bigNumber.multiply(someOtherBigNumber);

假设我们已经创建了另一个BigInteger

编辑 :正如评论中指出的那样,您需要删除二进制字符串表示中的空格,这很容易 - 我已经更新了我的答案以包含此步骤。

最简单的解决方案是使用BigInteger和基数2。

BigInteger multiply = new BigInteger("01100010...01100010", 2)
   .multiply(new BigInteger("01100011", 2));

System.out.println(multiply.toString(2));

相关问题:

下面使用带基数的BigInteger进行实际算术,并以十进制和二进制形式输出结果。

String s1 = "01100010 00110110 ...";
String s2 = "01100011";
s1 = s1.replaceAll(" ", "");
s2 = s2.replaceAll(" ", "");
BigInteger i1 = new BigInteger(s1, 2);
BigInteger i2 = new BigInteger(s2, 2);
BigInteger res = i1.multiply(i2);
System.out.println(res);
System.out.println(res.toString(2));

通过为二进制指定基数为2来使用BigInteger:

BigInteger num = new BigInteger(stringVar,2);  

这将另一个值乘以它:

BigInteger result = num.multiply(new BigInteger("01100011",2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM