views:

99

answers:

4

Hello All...

I Have one situation where I need to convert integer value into hexadecimal way.

I have done with some logical, but I want the optimized solutions...

Thanks in advance...

EDIT : Sorry I forgot to post that I am not allowed to use any in-built functions.

+4  A: 

Easy:

String hex = Integer.toHexString(int);

Basically what this does is creating a new string, and then calling a method from the Integer class called toHexString which needs an int arg. So pass the int you wanna change into this method and you'll get a String with the hexadecimal version of your int back.

You can put hexadecimal values in int types, but you cannot convert from int type to another int type, as far as i know, when you are doing hexadecimal conversions.

Remember that the value you get back is a String, so you cannot modify the value, otherwise you'll get an number format exception.

BryCry
+4  A: 

Well then have a look at the implementation of Integer.toHexString(int). The following code is extracted from the Integer class in the java standard library.

public class Test {

    final static char[] digits = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f'
    };

    private static String intAsHex(int i) {
        char[] buf = new char[32];
        int charPos = 32;
        int radix = 1 << 4;
        int mask = radix - 1;
        do {
            buf[--charPos] = digits[i & mask];
            i >>>= 4;
        } while (i != 0);

        return new String(buf, charPos, (32 - charPos));
    }


    public static void main(String... args) {
        System.out.println(intAsHex(77));
    }
}

Output: 4d

aioobe
If this is the standard library implementation then I'm surprised they allocate an array four times as large as will ever be needed!
mikera
+3  A: 

Assuming you don't want to use the built in toHexString for some reason, here's one pretty efficient way to do it:

 public static char toHexChar(int i) {
  i&=15;
  return (i<10)? (char)(i+48) : (char)(i+55);
 }

 public static String toHexString(int n) {
  char[] chars=new char[8];
  for (int i=0; i<8; i++) {
   chars[7-i]=toHexChar(n);
   n>>=4;
  };
  return new String(chars);
 }
mikera
This prints leading zeros, right? Like `00000005` for input `5`?
aioobe
Note this implementation always returns an answer in eight hex digits... this is probably what you want in most cases though if you want to exactly match the built in Java function you will want to remove the leading zeroes.
mikera
@aioobe that is right. Matter of taste I think but I always like to keep the leading zeroes to remind me that I'm dealing with a 32-bit binary quantity
mikera
+1  A: 

Check this

public class IntToHexa {
    public static void main(java.lang.String args[]){
        /*
         * Here we need an integer to convert.
         * [1]You can pass as command line argument
         * [2]You can get as input from console
         * [3]Take a constant. Here I'm taking a constant
         */
        int intToConvert = 450;
        java.lang.StringBuilder convertedHexa = new java.lang.StringBuilder("");
        while (intToConvert > 15){
            /*
         * If the reminder is less than 10, add the remainder. else get the equivalent hexa code
         * Here I'm getting the character code and adding the charater to the hexa string.
         * For that I'm getting the difference between the reminder and 10.
         * For example, if the reminder is 13, the reminder will be 3.
         * Then add that difference to 65. In this example, it will become 68.
         * Finally, get the quivalent char code of the result number. Here it will be D.
         * Same for number, I'm adding it to 48
         */
            convertedHexa.append(intToConvert % 16 < 10 ? ((char)(48 + (intToConvert % 16))) : ((char)(65 + (intToConvert % 16 - 10))));
            intToConvert /= 16;
        }
        convertedHexa.append(intToConvert % 16 < 10 ? ((char)(48 + (intToConvert % 16))) : ((char)(65 + (intToConvert % 16 - 10))));
        java.lang.System.out.println(convertedHexa.reverse());
    }
}
RaviG
This fails in various ways: e.g. produces strange values for 10-15. I suspect the "intToConvert % 16" will also do some strange things with negative numbers.
mikera
@mikera Fixed first point. Thanks for the comment.
RaviG