我使用以下方法将16位转换为带符号的十进制:
(short) Integer.parseInt("1110111100001010", 2))
问题是我有24位转换为带符号的十进制。
答案 0 :(得分:0)
使用没有大小限制的BigInteger。意味着无论二进制字符串有多大,都不会丢失任何数据。
为了使它签名,我参考这里讨论的一个简单技巧: Converting signed binary string in two's complement to int?
所以这里有两个方法:一个用于int,一个用于BigInt
public static String generateKString(String binary){
// k is the smallest positive number the actual binary scheme cannot represent
// for 1101 it is 1000
String kStr = "1";
for(int i = 1; i < binary.length(); i++)
kStr += "0";
return kStr;
}
public static BigInteger convertSignedBigInt(String binary){
BigInteger bInt = new BigInteger(binary, 2);
String kStr = generateKString(binary);
BigInteger k = new BigInteger(kStr, 2);
if (bInt.compareTo(k) == 1) bInt = bInt.subtract(k.multiply(new BigInteger("2")));
return bInt;
}
public static int convertSignedInt(String binary){
int i = Integer.parseInt(binary, 2);
String kStr = generateKString(binary);
int k = Integer.parseInt(kStr, 2);
if (i >= k) i -= 2 * k;
return i;
}