使用前导零将十六进制转换为二进制 [英] Converting hex to binary with leading zeros
问题描述
我正在关注下面的方法
new Biginteger(str,16).toString(2);
它工作得很好,但它消除了前导零。如果输入字符串为3031323334353637,则需要64位输出。
但返回62个字符。我可以使用for循环来做到这一点。有没有其他的方法可以做到这一点没有循环?
目标:将十六进制转换为带有前导零的二进制文件
您可以使用 String.format(%64s)
填充空格,然后将空格替换为<空格> <空格>零。这具有适用于任何大小输入的优势,而不仅限于int范围内的某些内容。我猜你正在使用BigInteger的任意输入......
字符串值= new BigInteger( 3031323334353637,16).toString(2);
System.out.println(String.format(%64s,value).replace(,0));
输出
0011000000110001001100100011001100110100001101010011011000110111
解释... String.format(%64s,value)前面的字符串填充为64个字符。
11000000110001001100100011001100110100001101010011011000110111
然后使用String.replace(oldString,newString)替换为'0'字符的前导空格
0011000000110001001100100011001100110100001101010011011000110111
I am following the below method
new Biginteger(str,16).toString(2);
It works really well, but it removes leading zeros. I need output in 64 bits if input string is "3031323334353637"
But it returns 62 characters. I can use a for loop to do that. Is there any other way to do that without loop?
Goal: Converting hex to binary with leading zeros
You can pad with spaces using String.format("%64s")
and then replace spaces with zeros. This has the advantage of working for any size of input, not just something in the int range. I'm guessing you're working with arbitrary inputs from your use of BigInteger...
String value = new BigInteger("3031323334353637", 16).toString(2);
System.out.println(String.format("%64s", value).replace(" ", "0"));
Output
0011000000110001001100100011001100110100001101010011011000110111
Explanation... The String.format("%64s, value) outputs the earlier String padded to fill 64 characters.
" 11000000110001001100100011001100110100001101010011011000110111"
The leading spaces are then replaced with '0' characters using String.replace(oldString, newString)
"0011000000110001001100100011001100110100001101010011011000110111"
这篇关于使用前导零将十六进制转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!