George Irimiciuc
George Irimiciuc

Reputation: 4633

How to add 0's in front of a binary number

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.

Upvotes: 0

Views: 2570

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213281

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');

Upvotes: 4

Related Questions