Decimal to Hexadecimal Converter in Java

后端 未结 13 2263
有刺的猬
有刺的猬 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);
    
    0 讨论(0)
  • 2020-12-03 14:24

    Here is the code for any number :

    import java.math.BigInteger;
    
    public class Testing {
    
    /**
     * @param args
     */
    static String arr[] ={"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}; 
    public static void main(String[] args) {
        String value = "214";
        System.out.println(value + " : " + getHex(value));
    }
    
    
    public static String getHex(String value) {
        String output= "";
        try {
            Integer.parseInt(value);
            Integer number = new Integer(value);
            while(number >= 16){
                output = arr[number%16] + output;
                number = number/16;
            }
            output = arr[number]+output;
    
        } catch (Exception e) {
            BigInteger number = null;
            try{
                number = new BigInteger(value);
            }catch (Exception e1) {
                return "Not a valid numebr";
            }
            BigInteger hex = new BigInteger("16");
            BigInteger[] val = {};
    
            while(number.compareTo(hex) == 1 || number.compareTo(hex) == 0){
                val = number.divideAndRemainder(hex);
                output = arr[val[1].intValue()] + output;
                number = val[0];
            }
            output = arr[number.intValue()] + output;
        }
    
        return output;
    }
    
    }
    
    0 讨论(0)
  • 2020-12-03 14:26

    Code to convert DECIMAL -to-> BINARY, OCTAL, HEXADECIMAL

    public class ConvertBase10ToBaseX {
        enum Base {
            /**
             * Integer is represented in 32 bit in 32/64 bit machine.
             * There we can split this integer no of bits into multiples of 1,2,4,8,16 bits
             */
            BASE2(1,1,32), BASE4(3,2,16), BASE8(7,3,11)/* OCTAL*/, /*BASE10(3,2),*/ 
            BASE16(15, 4, 8){       
                public String getFormattedValue(int val){
                    switch(val) {
                    case 10:
                        return "A";
                    case 11:
                        return "B";
                    case 12:
                        return "C";
                    case 13:
                        return "D";
                    case 14:
                        return "E";
                    case 15:
                        return "F";
                    default:
                        return "" + val;
                    }
    
                }
            }, /*BASE32(31,5,1),*/ BASE256(255, 8, 4), /*BASE512(511,9),*/ Base65536(65535, 16, 2);
    
            private int LEVEL_0_MASK;
            private int LEVEL_1_ROTATION;
            private int MAX_ROTATION;
    
            Base(int levelZeroMask, int levelOneRotation, int maxPossibleRotation) {
                this.LEVEL_0_MASK = levelZeroMask;
                this.LEVEL_1_ROTATION = levelOneRotation;
                this.MAX_ROTATION = maxPossibleRotation;
            }
    
            int getLevelZeroMask(){
                return LEVEL_0_MASK;
            }
            int getLevelOneRotation(){
                return LEVEL_1_ROTATION;
            }
            int getMaxRotation(){
                return MAX_ROTATION;
            }
            String getFormattedValue(int val){
                return "" + val;
            }
        }
    
        public void getBaseXValueOn(Base base, int on) {
            forwardPrint(base, on);
        }
    
        private void forwardPrint(Base base, int on) {
    
            int rotation = base.getLevelOneRotation();
            int mask = base.getLevelZeroMask();
            int maxRotation = base.getMaxRotation();
            boolean valueFound = false;
    
            for(int level = maxRotation; level >= 2; level--) {
                int rotation1 = (level-1) * rotation;
                int mask1 = mask << rotation1 ;
                if((on & mask1) > 0 ) {
                    valueFound = true;
                }
                if(valueFound)
                System.out.print(base.getFormattedValue((on & mask1) >>> rotation1));
            }
            System.out.println(base.getFormattedValue((on & mask)));
        }
    
        public int getBaseXValueOnAtLevel(Base base, int on, int level) {
            if(level > base.getMaxRotation() || level < 1) {
                return 0; //INVALID Input
            }
            int rotation = base.getLevelOneRotation();
            int mask = base.getLevelZeroMask();
    
            if(level > 1) {
                rotation = (level-1) * rotation;
                mask = mask << rotation;
            } else {
                rotation = 0;
            }
    
    
            return (on & mask) >>> rotation;
        }
    
        public static void main(String[] args) {
            ConvertBase10ToBaseX obj = new ConvertBase10ToBaseX();
    
            obj.getBaseXValueOn(Base.BASE16,12456); 
    //      obj.getBaseXValueOn(Base.BASE16,300); 
    //      obj.getBaseXValueOn(Base.BASE16,7); 
    //      obj.getBaseXValueOn(Base.BASE16,7);
    
            obj.getBaseXValueOn(Base.BASE2,12456);
            obj.getBaseXValueOn(Base.BASE8,12456);
            obj.getBaseXValueOn(Base.BASE2,8);
            obj.getBaseXValueOn(Base.BASE2,9);
            obj.getBaseXValueOn(Base.BASE2,10);
            obj.getBaseXValueOn(Base.BASE2,11);
            obj.getBaseXValueOn(Base.BASE2,12);
            obj.getBaseXValueOn(Base.BASE2,13);
            obj.getBaseXValueOn(Base.BASE2,14);
            obj.getBaseXValueOn(Base.BASE2,15);
            obj.getBaseXValueOn(Base.BASE2,16);
            obj.getBaseXValueOn(Base.BASE2,17);
    
    
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 1)); 
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 2)); 
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 3)); 
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE2, 4, 4)); 
    
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,15, 1)); 
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,30, 2)); 
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,7, 1)); 
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE16,7, 2)); 
    
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 511, 1)); 
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 511, 2)); 
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 512, 1));
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 512, 2)); 
            System.out.println(obj.getBaseXValueOnAtLevel(Base.BASE256, 513, 2)); 
    
    
        }
    }
    
    0 讨论(0)
  • 2020-12-03 14:32

    The easiest way to do this is:

    String hexadecimalString = String.format("%x", integerValue);
    
    0 讨论(0)
  • 2020-12-03 14:39

    Here's mine

    public static String dec2Hex(int num)
    {
        String hex = "";
    
        while (num != 0)
        {
            if (num % 16 < 10)
                hex = Integer.toString(num % 16) + hex;
            else
                hex = (char)((num % 16)+55) + hex;
            num = num / 16;
        }
    
        return hex;
    }
    
    0 讨论(0)
  • 2020-12-03 14:40

    Another possible solution:

    public String DecToHex(int dec){
      char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                  'A', 'B', 'C', 'D', 'E', 'F'};
      String hex = "";
      while (dec != 0) {
          int rem = dec % 16;
          hex = hexDigits[rem] + hex;
          dec = dec / 16;
      }
      return hex;
    }
    
    0 讨论(0)
提交回复
热议问题