Roloc
Roloc

Reputation: 1930

Convert hex string to int

I am trying to convert a string that is 8 characters long of hex code into an integer so that I can do int comparison instead of string comparisons over a lot of different values.

I know this is fairly trivial in C++ but I need to do it in Java. The test case I need to satisfy is essentially to Convert "AA0F245C" to int and then back to that string so that I know it is converting right.

I have tried the following:

int decode = Integer.decode("0xAA0F245C");  // NumberFormatException
int decode2 = Integer.decode("AA0F245C"); //NumberFormatException
int parseInt = Integer.parseInt("AA0F245C", 16); //NumberFormatException
int valueOf = Integer.valueOf("AA0F245C", 16); //NumberFormatException

I have also tried doing it two characters at a time and multiplying the results, which the conversion works but the number is not right.

int id = 0;
for (int h = 0; h < hex.length(); h= h+2)
{
    String sub = hex.subSequence(h, h+2).toString();

if (id == 0)
    id = Integer.valueOf(sub, 16);
else
    id *= Integer.valueOf(sub, 16);             
 }
//ID = 8445600 which = 80DEA0 if I convert it back. 

I can not use third party libraries just so you know, so this has to be done in Java standard libraries.

Thank you for your help in advance.

Upvotes: 137

Views: 246751

Answers (9)

heat
heat

Reputation: 1335

you can easily do it with parseInt with format parameter.

Integer.parseInt("-FF", 16) ; // returns -255

javadoc Integer

Upvotes: 15

Josko Marsic
Josko Marsic

Reputation: 61

Try with this:

long abc=convertString2Hex("1A2A3B");

private  long  convertString2Hex(String numberHexString)
{
    char[] ChaArray = numberHexString.toCharArray();
    long HexSum=0;
    long cChar =0;

    for(int i=0;i<numberHexString.length();i++ )
    {
        if( (ChaArray[i]>='0') && (ChaArray[i]<='9') )
            cChar = ChaArray[i] - '0';
        else
            cChar = ChaArray[i]-'A'+10;
        HexSum = 16 * HexSum + cChar;
    }
    return  HexSum;
}

Upvotes: 0

Javaru
Javaru

Reputation: 31936

An additional option to the ones suggested, is to use the BigInteger class. Since hex values are often large numbers, such as sha256 or sha512 values, they will easily overflow an int and a long. While converting to a byte array is an option as other answers show, BigInterger, the often forgotten class in java, is an option as well.

String sha256 = "65f4b384672c2776116d8d6533c69d4b19d140ddec5c191ea4d2cfad7d025ca2";
BigInteger value = new BigInteger(sha256, 16);
System.out.println("value = " + value);
// 46115947372890196580627454674591875001875183744738980595815219240926424751266

Upvotes: 4

Nitish Kumar
Nitish Kumar

Reputation: 11

//Method for Smaller Number Range:
Integer.parseInt("abc",16);

//Method for Bigger Number Range.
Long.parseLong("abc",16);

//Method for Biggest Number Range.
new BigInteger("abc",16);

Upvotes: 1

JanSmrz
JanSmrz

Reputation: 33

For those of you who need to convert hexadecimal representation of a signed byte from two-character String into byte (which in Java is always signed), there is an example. Parsing a hexadecimal string never gives negative number, which is faulty, because 0xFF is -1 from some point of view (two's complement coding). The principle is to parse the incoming String as int, which is larger than byte, and then wrap around negative numbers. I'm showing only bytes, so that example is short enough.

String inputTwoCharHex="FE"; //whatever your microcontroller data is

int i=Integer.parseInt(inputTwoCharHex,16);
//negative numbers is i now look like 128...255

// shortly i>=128
if (i>=Integer.parseInt("80",16)){

    //need to wrap-around negative numbers
    //we know that FF is 255 which is -1
    //and FE is 254 which is -2 and so on
    i=-1-Integer.parseInt("FF",16)+i;
    //shortly i=-256+i;
}
byte b=(byte)i;
//b is now surely between -128 and +127

This can be edited to process longer numbers. Just add more FF's or 00's respectively. For parsing 8 hex-character signed integers, you need to use Long.parseLong, because FFFF-FFFF, which is integer -1, wouldn't fit into Integer when represented as a positive number (gives 4294967295). So you need Long to store it. After conversion to negative number and casting back to Integer, it will fit. There is no 8 character hex string, that wouldn't fit integer in the end.

Upvotes: 3

HannahCarney
HannahCarney

Reputation: 3631

This is the right answer:

myPassedColor = "#ffff8c85" int colorInt = Color.parseColor(myPassedColor)

Upvotes: 9

Manikant Gautam
Manikant Gautam

Reputation: 3591

you may use like that

System.out.println(Integer.decode("0x4d2"))    // output 1234
//and vice versa 
System.out.println(Integer.toHexString(1234); //  output is 4d2);

Upvotes: 57

Incompl
Incompl

Reputation: 421

The maximum value that a Java Integer can handle is 2147483657, or 2^31-1. The hexadecimal number AA0F245C is 2853119068 as a decimal number, and is far too large, so you need to use

Long.parseLong("AA0F245C", 16);

to make it work.

Upvotes: 21

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

It's simply too big for an int (which is 4 bytes and signed).

Use

Long.parseLong("AA0F245C", 16);

Upvotes: 177

Related Questions