将十六进制字符串转换为32位二进制字符串

时间:2023-01-08 15:46:05

How can I convert a Hex String into 32bit Binary String? I did

如何将十六进制字符串转换为32位二进制字符串?我做到了

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

To get the Binary String, but I need to pad it with 0's to ensure its 32 bits, how can I do that, preferably with Formatter?

要获取二进制字符串,但我需要用0来填充以确保其32位,我该怎么做,最好使用Formatter?

1 个解决方案

#1


0  

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

The idea here is to parse the string back in as a decimal number temporarily (one that just so happens to consist of all 1's and 0's) and then use String.format().

这里的想法是暂时将字符串解析为十进制数字(恰好包含所有1和0),然后使用String.format()。

Note that you basically have to use BigInteger, because binary strings quickly overflow Integer and Long resulting in NumberFormatExceptions if you try to use Integer.fromString() or Long.fromString().

请注意,您基本上必须使用BigInteger,因为如果您尝试使用Integer.fromString()或Long.fromString(),二进制字符串会快速溢出Integer和Long,从而导致NumberFormatExceptions。

#1


0  

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

The idea here is to parse the string back in as a decimal number temporarily (one that just so happens to consist of all 1's and 0's) and then use String.format().

这里的想法是暂时将字符串解析为十进制数字(恰好包含所有1和0),然后使用String.format()。

Note that you basically have to use BigInteger, because binary strings quickly overflow Integer and Long resulting in NumberFormatExceptions if you try to use Integer.fromString() or Long.fromString().

请注意,您基本上必须使用BigInteger,因为如果您尝试使用Integer.fromString()或Long.fromString(),二进制字符串会快速溢出Integer和Long,从而导致NumberFormatExceptions。