tags:

views:

136

answers:

10

Hi,

I'm reading file and I want to print byte value in 2 digits if it is less than 10 (example if byte=1 it should disply byte=01), I don't want to compare it like this:

    if(byte<10){
        stringBuffer buf= new stringBuffer();
        buf.append("0"+byte);
    }

is there any built in method to do this, just like the format function in vc++?

Thanks gagana

+2  A: 

See java.util.Formatter

Mark
+1  A: 

java.util.Formatter

moonshadow
A: 

Take a look at the Formatter class

Brian Agnew
+5  A: 

How about:

String twoDigits = String.format("%02d", myByte);

It's a lot closer to the C way of doing things rather than having to instantiate your own formatter.

paxdiablo
A: 
byte b = ...
System.out.println(String.format("%02x",b));
David Rabinowitz
A: 

For "small" values of b this should be fine:

String s = "" + b;
while(s.length() < 2) {
   s = "0" + s;
 }
Thorbjørn Ravn Andersen
+3  A: 

You can use DecimalFormat:

NumberFormat nf = new DecimalFormat("00");
buf.append(df.format(byteArray[i]));

Obviously you just instantiate it once outside the loop.

cletus
+3  A: 
System.out.println(new DecimalFormat("00").format(9));

prints 09 for me.

Nico
+1  A: 

The 'a' is 10 in hexadecimal format.

So change your format strings from "%02x" to "%02d"

pavium
ya tried by %02d but same problem
but you definitely don't want hexadecimal format, it seems. Is the problem with %02d that you get 1000 instead of 0010 ?
pavium
A: 

I'm not so convenient with java syntax... But here is a way... May be you need to find equalant of right for java

buf.append(right(("00" + byte),2))

The King