1

Let's say i have this Long in Java:

 Long x=0b01101L;

and i want to convert it into a String using this:

String str1 = Long.toBinaryString(x);

Is there a way to keep the first 0 inside the String? What i mean is can this:

System.out.println(str1); 

print 01101 and not 1101?

Epitheoritis 32
  • 332
  • 3
  • 12
  • 1
    Try this: https://stackoverflow.com/questions/4421400/how-to-get-0-padded-binary-representation-of-an-integer-in-java – Palash Goel Aug 13 '19 at 12:54
  • why only one zero? the long has plenty more zeros (and there is no difference between `Long x=0b01101L;` and `Long x=0b0000000000001101L`, after compilation both are just `13L`) – user85421 Aug 13 '19 at 13:42

1 Answers1

3

This is not possible. When you declare Long x = 0b01101L;, you create a long instance, which contains no information about the String representation of the value it contains. Yes, it equals 13 in decimal, but it also equals 十三 in traditional Chinese/Japanese writing, and it also equals 10 + 3, and so on.

If you want to convert it to a String padded to a certain number of zeroes, you can use String.format("%16s", Integer.toBinaryString(x)).replace(' ', '0'), but you must know in advance how many digits you want to be printed, as this will always return 16 digits.

However, this information is not encoded in a Long (or long). If you need to keep this information, declare your variable as a String xString = "01101";, and convert it to a long using Long.valueOf(xString, 2); when you need to do numerical operations.

eHayik
  • 2,311
  • 1
  • 14
  • 22
cameron1024
  • 2,931
  • 1
  • 8
  • 19