简体   繁体   English

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

[英]Converting a Hex String into 32 Bit Binary String

How can I convert a Hex String into 32bit Binary String? 如何将十六进制字符串转换为32位二进制字符串? I did 我做了

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?

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM