Question

int g = 269;
System.out.println( Integer.toBinaryString(g));//100001101
g<<=10;
System.out.println( Integer.toBinaryString(g));//1000011010000000000

I know I can do it like this to add "0"'s after the number, but what if I want to add them before it?

g>>=1; won't work, obviously.

Était-ce utile?

La solution

It doesn't make sense to print leading zero for an integer, or it's binary representation. How many of them you would like to print? And how would compiler know that on it's own. However, you can always format your string to be padded with zero like this:

int g = 269;
String paddedWithZero = String.format("%32s", Integer.toBinaryString(g)).replace(' ', '0');
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top