Convert zero to byte

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

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

      

is there a built-in method for this, just like the format function in vc ++?

Thanks gagana

+2


source to share


10 replies


What about:

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

      



This is much closer to the way things are done, rather than creating your own formatting.

+5


source


You can use DecimalFormat

:

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

      



Obviously, you are just instantiating it outside of the loop.

+3


source


System.out.println(new DecimalFormat("00").format(9));

      

prints 09 for me.

+3


source


+2


source


+1


source


"a" is 10 in hexadecimal.

So change the format lines from "% 02x" to "% 02d"

+1


source


Take a look at the Formatter class

0


source


byte b = ...
System.out.println(String.format("%02x",b));

      

0


source


For "small" values โ€‹โ€‹of b, this should be fine:

String s = "" + b;
while(s.length() < 2) {
   s = "0" + s;
 }

      

0


source


I'm not very comfortable with the java syntax ... But here's the way ... Maybe you need to find the equal on the right for java

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

0


source







All Articles