Reputation: 366
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
?
Upvotes: 1
Views: 366
Reputation: 10156
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.
Upvotes: 3