how to use format?

N

nick

for (int j = 0; j <= 7; j++) {
System.out.println(Integer.toBinaryString(j));
}


the result:
0
1
10
11
......

how to make the print result become:
00000
00001
00010
00011
.........


thanks!
 
S

Skip

nick said:
for (int j = 0; j <= 7; j++) {
System.out.println(Integer.toBinaryString(j));
}


the result:
0
1
10
11
.....

how to make the print result become:
00000
00001
00010
00011
........

String binary = Integer.toBinaryString(...));
int fixedLenght = 8;
int currentLength = binary.length();
int difference = fixedLength - currentLength;

StringBuffer sb = new StringBuffer();
for(int i=0; i<difference; i++)
{
sb.append('0');
}
sb.append(binary);

binary = sb.toString();

~~

HTH
 
B

Babu Kalakrishnan

Andrew said:
java.text.DecimalFormat

Not really recommended. DecimalFormat (as the name indicates) formats
numbers using Base 10 - Not binary. So you'd have to 3 conversions :
first to a binary string - then convert it to a decimal number and then
use decimalformat for formatting, which is overkill.

May be something like :

public static String createBinaryString(int number, int minDigits)
{
// assert that digits <= 31
// Will need to use long if digits > 31

int orMask = 1 << minDigits;

if (number < 0 ||
(orMask > 0 &&
number >= orMask)) // result will be longer
{
return Integer.toBinaryString(number);
} else
{
String s = Integer.toBinaryString(number | orMask);
return s.substring(1);
}
}

BK
 
K

Kieron Briggs

Skip said:
String binary = Integer.toBinaryString(...));
int fixedLenght = 8;
int currentLength = binary.length();
int difference = fixedLength - currentLength;

StringBuffer sb = new StringBuffer();
for(int i=0; i<difference; i++)
{
sb.append('0');
}
sb.append(binary);

binary = sb.toString();

Or how about:

StringBuffer sb = new StringBuffer(Integer.toBinaryString(...));
while (sb.length() < DESIRED_LENGTH) {
sb.insert(0, '0');
}
System.out.println(sb.toString());

Just saves a few variables... ;-)



Kieron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top