Kakashi - Sensei
Kakashi - Sensei

Reputation: 381

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

Upvotes: 1

Views: 3027

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

Java 17+

You can use HexFormat to convert an Integer to a hexadecimal string e.g.

import java.util.HexFormat;

class Main {
    public static void main(String[] args) {
        int x = 229;

        HexFormat hex = HexFormat.of();
        System.out.println(hex.toHexDigits(x));

        HexFormat hexUpper = HexFormat.of().withUpperCase();
        System.out.println(hexUpper.toHexDigits(x));
    }
}

Output:

000000e5
000000E5

Upvotes: 3

Abdo Bmz
Abdo Bmz

Reputation: 641

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

Upvotes: 4

Related Questions