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
PS T1 and T2 are two user-subitted imputs.
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
0
s.
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');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.