2011-11-20 306 views
0

如何將十六進制字符串轉換爲32位二進制字符串?我做將十六進制字符串轉換爲32位二進制字符串

String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16)); 

爲了得到二進制串,但我需要填充它用0,以確保其32位,我怎麼能做到這一點,最好用格式化?

+0

[(Java)指定將二進制數字轉換爲字符串時的位數(長度)](http://stackoverflow.com/questions/625838/java-specify-number-of-bits-length-當轉換二進制數到字符串) – 2011-11-20 09:02:47

+0

更簡單的答案在這裏雖然... – jkschneider

回答

0
String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16)); 
String.format("%032", new BigInteger(binAddr)); 

這裏的想法是解析字符串返回的十進制數暫時(一說只是恰巧包括所有的1和0),然後使用String.format()

請注意,您基本上必須使用BigInteger,因爲如果您嘗試使用Integer.fromString()Long.fromString(),則二進制字符串會快速溢出整型和長整型,從而導致NumberFormatExceptions。

相關問題