Decimal to Hexadecimal Converter in Java

后端 未结 13 2378
有刺的猬
有刺的猬 2020-12-03 13:57

I have a homework assignment where I need to do three-way conversion between decimal, binary and hexadecimal. The function I need help with is converting a decimal into a he

13条回答
  •  爱一瞬间的悲伤
    2020-12-03 14:24

    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);
    

提交回复
热议问题