简体   繁体   English

使用BigInteger,如何传递二进制数的符号以将其作为整数?

[英]Using BigInteger, how can I pass the sign of my binary number to get it as an int?

I'm trying to convert binary strings to signed decimal numbers. 我正在尝试将二进制字符串转换为带符号的十进制数字。 I am trying to figure out a way to do that with 10 bit binary strings. 我试图找出一种方法来处理10位二进制字符串。

String i = kb.next();
int p = new BigInteger(i, 2).intValue();

The above code will convert a binary string to a decimal number however you need to enter the sign and a 32-bit string. 上面的代码会将二进制字符串转换为十进制数字,但是您需要输入符号和32位字符串。 Is there anyway I could pass a 10-bit string and it return the correct decimal number. 无论如何,我可以传递一个10位的字符串,并返回正确的十进制数字。

I've checked the code you gave and it's still works. 我已经检查了您提供的代码,它仍然有效。 If you still want to pass a 32-bit String, however, you could use this code: 但是,如果仍然要传递32位字符串,则可以使用以下代码:

while(i.length()<32){
    i = "0"+i;
}

this code fill the given string with 0s before to make a 32-bit integer. 此代码在给定字符串之前用0填充,以生成32位整数。

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

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