0

I have these two lines of code that I need to modify so that they will always return four digits of binary.

    String binary1 = Integer.toBinaryString(t1);
    String binary2 = Integer.toBinaryString(t2);

    String first1 = binary1.substring(0,0);
    String first2 = binary2.substring(0,0);
    String second1 = binary1.substring(1,1);
    String second2 = binary2.substring(1,1);
    String third1 = binary1.substring(2,2);
    String third2 = binary2.substring(3,3);
    String fourth1 = binary1.substring(4,4);
    String fourth2 = binary2.substring(4,4);

Is there a method that cn controll the amount of digits in binary1 and binary2

P.S. T1 and T2 are two user-subitted imputs.

Amey Gupta
  • 57
  • 1
  • 10
  • possible duplicate of [Java integer to binary string](http://stackoverflow.com/questions/21856626/java-integer-to-binary-string) – PM 77-1 Apr 09 '15 at 01:30

1 Answers1

4

The Javadoc for Integer.toBinaryString(int) says (in part),

This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.

So, no. You cannot control the number of digits with toBinaryString(int). You might use String.format(String, Object...) like

String binary1 = String.format("%4s", Integer.toString(t1, 2))
    .replace(' ', '0');
String binary2 = String.format("%4s", Integer.toString(t2, 2))
    .replace(' ', '0');
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249