4

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

3 Answers 3

12

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can pad your binary string with zeroes.

String bin = String.format("%8s", Integer.toBinaryString(x).replace(' ', '0');

Comments

0

Convert, check the resulting length and add zeros if < 8.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.