Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

How to convert Decimal to Hexadecimal in Java?

1 Answer

0 votes
by (13.1k points)

You can try this:

import java.lang.StringBuilder;

class Test {

  private static final int sizeOfIntInHalfBytes = 8;

  private static final int numberOfBitsInAHalfByte = 4;

  private static final int halfByte = 0x0F;

  private static final char[] hexDigits = { 

    '0', '1', '2', '3', '4', '5', '6', '7', 

    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'

  };

  public static String decToHex(int dec) {

    StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);

    hexBuilder.setLength(sizeOfIntInHalfBytes);

    for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)

    {

      int j = dec & halfByte;

      hexBuilder.setCharAt(i, hexDigits[j]);

      dec >>= numberOfBitsInAHalfByte;

    }

    return hexBuilder.toString(); 

  }

  public static void main(String[] args) {

     int dec = 305445566;

     String hex = decToHex(dec);

     System.out.println(hex);       

  }

}

Output:
1234BABE

Also, there is a library to do this task:

String hex = Integer.toHexString(dec);

Want to learn Java? Check out the Core Java certification from Intellipaat.

Related questions

0 votes
1 answer
asked Oct 26, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Apr 14, 2021 in Java by Jake (7k points)
0 votes
0 answers
0 votes
1 answer
0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)

Browse Categories

...