22

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 hexadecimal. I have nearly no understanding of hexadecimal, nonetheless how to convert a decimal into hex. I need a function that takes in an int dec and returns a String hex. Unfortunately I don't have any draft of this function, I'm completely lost. All I have is this.

  public static String decToHex(int dec)
  {
    String hex = "";


    return hex;
  }

Also I can't use those premade functions like Integer.toHexString() or anything, I need to actually make the algorithm or I wouldn't have learned anything.

Bart
  • 19,692
  • 7
  • 68
  • 77
flyingpretzels
  • 233
  • 1
  • 3
  • 6
  • 10
    "I need to actually make the algorithm or I wouldn't have learned anything" -- good. However I'd take it a step further and say that if you want to learn something, you have to actually figure the algorithm out yourself (instead of someone giving it go you). If you are to be a software programmer, you need to be (or become) good at puzzles. This is a good exercise. – JimN Nov 20 '12 at 01:08
  • You can find the algorithms on the internet. They are very easy. :-) – assafmo Nov 20 '12 at 01:10
  • Yes, I understand. However, I've been sitting here scratching my head working on this. If I wasn't completely out of ideas and still had a clue on what to do, I wouldn't have come here to StackOverflow. – flyingpretzels Nov 20 '12 at 01:10
  • 1
    Do you have a understanding of hexadecimal counting? Like Binary counting, except instead of using 2 sets of numbers, you use 16. 0 = 0x0 1 = 0x1 ... 9 = 0x9 10 = 0xA 11 = 0xB ... 15 = 0XF 16 = 0X11 ... – Terrell Plotzki Nov 20 '12 at 01:12
  • I have a minimal understanding. I've watched some Youtube tutorial videos and understand the very basics, like A represents 10 and so on until F is 16 then you start a new set. That 0x0 and 0xA stuff, no idea. I'm just a sophomore in high school and we haven't even officially learned about hexes yet. – flyingpretzels Nov 20 '12 at 01:16
  • First hint: `int` is not decimal. Decimal is like `1253`. `int` is a numeric value that does not have an inherent representation, but can be represented as base 2 (binary), base 8 (octal), base 10 (decimal), or base 16 (hex), or, if you really want, base 27. What you want is routines to convert each base to/from an `int` internal representation. – Hot Licks Nov 20 '12 at 01:18
  • There's nothing special about ABCDEF being 10,11,12,13,14,15 -- it's just the most obvious assignment of symbols to base 16 digits. Imagine if we only had 8 fingers and only the numerals 0-7. Then we might represent decimal with the character A for 8 and B for 9. Or we could represent hex with the characters `!@#$%^` in place of the characters ABCDEF -- there's nothing special/sacred about the choices. – Hot Licks Nov 20 '12 at 01:22
  • This is a base conversion problem. Perhaps a good place to start would be an ASCII table - http://www.asciitable.com – Christian Trimble Nov 20 '12 at 01:25
  • I understand there's nothing special about 'ABCDEF'. But about the 'int' not being decimal... I think I understand what that literally means, like not all decimals are integers, and what you'd put in the 'int' variable can be represented in any base, but how? I know that for binary you get the remainder of the divisions of the number divided by 2... Is it just replace 2 with 16 in hex? – flyingpretzels Nov 20 '12 at 01:29
  • Study up on modulo division -- the `%` operator. Repeatedly divide a (integer) number by a base N and take the remainder portion (the result of `%` division) as a digit, while reducing your original value with `/` division. This will give you the digits of the number, in base N, from right to left. Eg, 27 decimal is hex 0x1B. So do `27 % 16` and you get 11. Do `27 / 16` and you get 1. Repeat with `1 % 16` gives you 1, and `1 / 16` gives you zero (meaning you're done). You've developed the digits 11 and 1, and 11 is B in hex, while 1 is, well, 1. So your result is 0x1B. – Hot Licks Nov 20 '12 at 01:38
  • Note that a single method can convert an integer to any base -- you just feed in N as a parameter. Going the other was is a matter of multiplication times N and addition (after converting the printable digit to it's pure numeric meaning). – Hot Licks Nov 20 '12 at 01:41
  • 2
    I figured it out! What you just said made perfect sense to me for converting to any base, and I combined it with an array of possible digits like kol had here, and it worked! And I actually get it! Thanks a lot! – flyingpretzels Nov 20 '12 at 01:45

12 Answers12

38

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);
kol
  • 27,881
  • 12
  • 83
  • 120
  • I believe you can also use Integer.parseInt – Vineet Kosaraju Nov 20 '12 at 01:56
  • 5
    Now the OP won't learn much from "doing" his homework. Well done ... NOT!! – Stephen C Nov 20 '12 at 02:56
  • 12
    @StephenC You are right, but then what is this site for? Helping people to do their homework is bad, but helping professional programmers to do their real work is not? Everyone could google up low quality solutions for their programming problems. SO makes the world a better place by collecting and selecting quality solutions. Anyway I do believe the OP could learn a lot from my solution :) – kol Nov 20 '12 at 07:47
  • 4
    @kol - no professional would *ever* ignore `Integer.toHexString()` and implement it his / herself. *"Anyway I do believe the OP could learn a lot from my solution"* - and I believe the OP would learn more important things if he / she DIDN'T read it. The point of the OP's homework it to learn how to program. You learn how to program by writing your own (to start with) ugly solutions, not by reading other peoples elegant solutions. – Stephen C Nov 20 '12 at 13:07
  • @StephenC *"no professional would ever ignore Integer.toHexString() and implement it his / herself"* This brings back memories... Few years ago in an interview test we asked the applicants to "write a Trim function in Delphi, C/C++, C# or Java". We wanted to test whether they could write a simple algorithm. It was shocking to realize that *every* applicant (out of approx. 25!) wrote a function, which simply called the built-in Trim function, and returned its result. Even the girl who proved to be the best did this. When I asked her why, she looked at me like I was an idiot :) – kol Nov 20 '12 at 13:32
  • But what if the number we want to convert is out of range of integer. – Ankit Singla Dec 05 '13 at 06:36
  • 1
    @AnkitSingla Then use `long` instead of `int` :) Or use `java.math.BigInteger`, and its `bitLength`, `and` and `rightShift` methods. There is also a built-in conversion method for `BigInteger`: `public String toString(int radix)`, just call it with `16` as the `radix`. – kol Dec 05 '13 at 21:17
29

Simple:

  public static String decToHex(int dec)
  {
        return Integer.toHexString(dec);
  }

As mentioned here: Java Convert integer to hex integer

Community
  • 1
  • 1
Andreas L.
  • 2,805
  • 23
  • 23
14

I need a function that takes in an int dec and returns a String hex.

I found a more elegant solution from http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html . I changed a bit from the original ( see the edit )

// precondition:  d is a nonnegative integer
public static String decimal2hex(int d) {
    String digits = "0123456789ABCDEF";
    if (d <= 0) return "0";
    int base = 16;   // flexible to change in any base under 16
    String hex = "";
    while (d > 0) {
        int digit = d % base;              // rightmost digit
        hex = digits.charAt(digit) + hex;  // string concatenation
        d = d / base;
    }
    return hex;
}

Disclaimer: I ask this question in my coding interview. I hope this solution doesn't get too popular :)

Edit June 17 2016 : I added the base variable to give the flexibility to change into any base : binary, octal, base of 7 ...
According to the comments, this solution is the most elegant so I removed the implementation of Integer.toHexString() .

Edit September 4 2015 : I found a more elegant solution http://introcs.cs.princeton.edu/java/31datatype/Hex2Decimal.java.html

Raymond Chenon
  • 11,482
  • 15
  • 77
  • 110
2

Consider dec2m method below for conversion from dec to hex, oct or bin.

Sample output is

28 dec == 11100 bin 28 dec == 34 oct 28 dec == 1C hex

public class Conversion {
    public static void main(String[] argv) {
        int x = 28;                           // sample number
        if (argv.length > 0)
            x = Integer.parseInt(argv[0]);    // number from command line

        System.out.printf("%d dec == %s bin\n", i, dec2m(x, 2));
        System.out.printf("%d dec == %s oct\n", i, dec2m(x, 8));
        System.out.printf("%d dec == %s hex\n", i, dec2m(x, 16));
    }

    static String dec2m(int N, int m) {
        String s = "";
        for (int n = N; n > 0; n /= m) {
            int r = n % m;
            s = r < 10 ? r + s : (char) ('A' - 10 + r) + s;
        }
        return s;
    }
}
Andrej
  • 129
  • 3
1

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

}
Ankit Singla
  • 198
  • 2
  • 15
1

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;
}
Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118
  • 1
    Code only answers don't say much. Please add some explanation as to why you think your code is a solution. – rgettman Feb 10 '15 at 22:37
  • Do you have the implementation to convert back from HEX STRING to Integer ? Or imagie I desire to change the Digits and create diferent base , for example base 20 ? – MadMad666 May 19 '15 at 15:49
1

The easiest way to do this is:

String hexadecimalString = String.format("%x", integerValue);
Serenity
  • 35,289
  • 20
  • 120
  • 115
Skilla
  • 31
  • 2
0

I will use

Long a = Long.parseLong(cadenaFinal, 16 );

since there is some hex that can be larguer than intenger and it will throw an exception

D4rWiNS
  • 2,585
  • 5
  • 32
  • 54
  • This solution reads a string containing a hexadecimal representation of a number and returns a long with that value. This is, in other words, not what the OP asked for. – klaar Oct 30 '15 at 10:11
  • 1
    I just let it there if someone get the same problem as me, just in case – D4rWiNS Oct 30 '15 at 10:59
0

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


    }
}
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101
0

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;
}
Idan
  • 111
  • 1
  • 1
  • 4
0

A better solution to convert Decimal To HexaDecimal and this one is less complex

import java.util.Scanner;
public class DecimalToHexa
{
    public static void main(String ar[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter a Decimal number: ");
        int n=sc.nextInt();
        if(n<0)
        {
            System.out.println("Enter a positive integer");
            return;
        }
        int i=0,d=0;
        String hx="",h="";
        while(n>0)
        {
            d=n%16;`enter code here`
            n/=16;
            if(d==10)h="A";
            else if(d==11)h="B";
            else if(d==12)h="C";
            else if(d==13)h="D";
            else if(d==14)h="E";
            else if(d==15)h="F";
            else h=""+d;            
            hx=""+h+hx;
        }
        System.out.println("Equivalent HEXA: "+hx);
    }
}        
0

The following converts decimal to Hexa Decimal with Time Complexity : O(n) Linear Time with out any java inbuilt function

private static String decimalToHexaDecimal(int N) {
    char hexaDecimals[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    StringBuilder builder = new StringBuilder();
    int base= 16;
    while (N != 0) {
        int reminder = N % base;
        builder.append(hexaDecimals[reminder]);
        N = N / base;
    }

    return builder.reverse().toString();
}