Search code examples
javaintegerhexnumber-formatting

how to convert decimal to hexadecimal in java


I need to convert the rest of the division by 16 to Hexadecimal. I'm using the Integer.toHexString method and pass the value (variable "resto") that I need to convert to hexadecimal, but the ouput value is not in hexadecimal.

int total = 50;
resto = total / 16;
String decimal = Integer.toHexString(resto);
System.out.println(decimal);

outputs 3


Solution

  • Using toHexString() method of Integer class.

    Exmple :

    import java.util.Scanner;
    class DecimalToHexExample
    {
        public static void main(String args[])
        {
          Scanner input = new Scanner( System.in );
          System.out.print("Enter a decimal number : ");
          int num =input.nextInt();
    
          // calling method toHexString()
          String str = Integer.toHexString(num);
          System.out.println("Decimal to hexadecimal: "+str);
        }
    }
    

    Output:

    Enter a decimal number : 123
    Decimal to hexadecimal: 7b