"decimal to hexadecimal converter in java" Code Answer

1

one possible solution:

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

anyway, there is a library method for this:

string hex = integer.tohexstring(dec);
By mattyohe on January 31 2022

Answers related to “decimal to hexadecimal converter in java”

Only authorized users can answer the Search term. Please sign in first, or register a free account.