如何在 Java 中将二进制字符串转换为以 10 为底的整数

2022-01-09 00:00:00 string binary java radix

我有一个表示二进制数(不带前导零)的字符串数组,我想将其转换为相应的以 10 为基数的数字.考虑:

I have an array of Strings that represent Binary numbers (without leading zeroes) that I want to convert to their corresponding base 10 numbers. Consider:

binary 1011 becomes integer 11
binary 1001 becomes integer 9
binary   11 becomes integer 3   etc. 

最好的方法是什么?我一直在探索 java.lang.number.* 却没有找到直接的转换方法.Integer.parseInt(b) 产生一个与字符串相等的整数...例如,1001 变为 1,001 而不是 9...并且似乎不包含输出基数的参数.toBinaryString 转换方向错误.我怀疑我需要进行多步转换,但似乎找不到正确的方法或子类组合.我也不确定前导零或缺少前导零会在多大程度上成为问题.有人有什么好的方向可以指点我吗?

What's the best way to proceed? I've been exploring java.lang.number.* without finding a direct conversion method. Integer.parseInt(b) yields an integer EQUAL to the String...e.g., 1001 becomes 1,001 instead of 9...and does not seem to include a parameter for an output base. toBinaryString does the conversion the wrong direction. I suspect I'll need to do a multistep conversion, but can't seem to find the right combination of methods or subclasses. I'm also not sure the extent to which leading zeros or lack thereof will be an issue. Anyone have any good directions to point me?

推荐答案

你需要指定基数.Integer#parseInt() 的重载允许您这样做.

You need to specify the radix. There's an overload of Integer#parseInt() which allows you to.

int foo = Integer.parseInt("1001", 2);

相关文章