Java - Format integer as base 8 and base-16

Introduction

When conversions 'o' and 'x' are used with a negative argument of byte, Byte, short, Short, int, Integer, long, and Long data types, the argument value is converted to an unsigned number by adding a number 2N to it, where N is the number of bits used to represent the value of the data type of the argument.

For example, if the argument data type is byte, which takes 8 bits to store the value, the argument value of -X will be converted to a positive value of -X + 256 by adding 256 to it and the result contain the base-8 or base-16 equivalent of the value -X + 256.

The conversions 'o' and 'x' do not transform the negative argument value to an unsigned value for a BigInteger argument type.

Consider the following code:

Demo

public class Main {
  public static void main(String[] args) {
    byte b1 = 9;//from   ww w  . ja va2  s  .c o  m
    byte b2 = -9;
    System.out.printf("%o %n", b1);
    System.out.printf("%o %n", b2);
  }
}

Result

The conversion 'o' outputs the base-8 integer 11 for a positive decimal integer 9.

However, when a negative decimal integer -9 is used with the 'o' conversion, -9 is converted to a positive number -9 + 256 (=247).

The final output contains 367, which is the base-8 equivalent of the decimal 247.

The following code shows some more examples of 'o' and 'x' conversions for int and BigInteger argument types:

Demo

import java.math.BigInteger;

public class Main {
  public static void main(String[] args) {
    System.out.printf("%o %n", 2028);
    System.out.printf("%o %n", -2028);
    System.out.printf("%o %n", new BigInteger("2028"));
    System.out.printf("%o %n", new BigInteger("-2028"));

    System.out.printf("%x %n", 2028);
    System.out.printf("%x %n", -2028);
    System.out.printf("%x %n", new BigInteger("2028"));
    System.out.printf("%x %n", new BigInteger("-2028"));

    System.out.printf("%#o %n", 2028);
    System.out.printf("%#x %n", 2028);
    System.out.printf("%#o %n", new BigInteger("2028"));
    System.out.printf("%#x %n", new BigInteger("2028"));
  }/*from   w w w .j  a va  2  s  .c o m*/
}

Result

Locale

Many locale-specific formatting are automatically applied when a numeric value is formatted.

The following code shows the same number 1234567890 formatted differently for three different locales US, Indian, and Thailand:

Demo

import java.util.Locale;

public class Main {
  public static void main(String[] args) {
    Locale englishUS = new Locale("en", "US");
    Locale hindiIndia = new Locale("hi", "IN");
    Locale thaiThailand = new Locale("th", "TH", "TH");
    System.out.printf(englishUS, "%d %n", 1234567890);
    System.out.printf(hindiIndia, "%d %n", 1234567890);
    System.out.printf(thaiThailand, "%d %n", 1234567890);

  }//w  ww . j  a v a  2  s .c  o  m
}

Result

Related Topic