Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

java - Convert integer to zero-padded binary string

when converting int to binary, how to output it to 8 character, currently it only display 1 and short of the 7 zeros

code

int x = 1;
String bin = Integer.toBinaryString(x);
System.Out.Println(bin);

example output to 0000 0001

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am not sure if that is what you mean but how about something like

String.format("%8s", Integer.toBinaryString(1)).replace(' ', '0')

will generate 00000001


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...