2

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

Gibbs
  • 16,706
  • 11
  • 53
  • 118

3 Answers3

7

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"
Adam
  • 32,907
  • 8
  • 89
  • 126
  • Thanks. It works. But I am trying to understand your solution. First stmt returns 62 characters. In the sec stmt, creating width 64 and value gets stored in that 64 bits. High order bits will have 2 spaces in this example.it gets replaceed by 0. Am I right? Please let me know – Gibbs Aug 24 '15 at 16:13
  • I've added some more details on how it works.... Let me know if that helps fully explains it. – Adam Aug 25 '15 at 05:36
  • Thanks Man :) I understood – Gibbs Aug 25 '15 at 09:10
1

Check out this question.

You can do it using String.format():

String unpaddedBinary = new BigInteger("a12", 16).toString(2);
String paddedBinary = String.format("%064s", Integer.parseInt(unpaddedBinary, 2));
Community
  • 1
  • 1
Anubian Noob
  • 12,897
  • 5
  • 47
  • 69
  • 2
    The output of that is 0000000000000000000000000000000000000000000000000000000000002578... Surely that's not correct... %064d" formats to decimal, not binary... – Adam Aug 24 '15 at 15:46
  • 2
    You could also just convert the `BigInteger` to `int` directly using `BigInteger.intValue`. Although if it fits in an `int`, one should probably just use an `int` in the first place (rather than `BigInteger`), and if it doesn't fit in an `int`, this won't work. – Bernhard Barker Aug 24 '15 at 15:48
  • @Dukeling oh my bad, refer to [Adam's answer](http://stackoverflow.com/a/32186351/2197700) instead, his seems to be correct. – Anubian Noob Aug 24 '15 at 15:57
1

If your Hex string is always going to be 16 characters, the following may be the easiest:

new BigInteger("1" + str,16).toString(2).substring(1)

Dakshinamurthy Karra
  • 4,969
  • 1
  • 13
  • 25