問題描述
我有一個表示二進制數(不帶前導零)的字符串數組,我想將其轉換為相應的以 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);
這篇關于如何在 Java 中將二進制字符串轉換為以 10 為底的整數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!