HimanshuR
HimanshuR

Reputation: 1438

convert string to hexadecimal string

i have a string of int value like "131008130225002" i need to convert it to hexadecimal string. I tried various ways,

  1. output of toHex function is 313331303038313330323235303032 but i do not need it,
  2. i need in hexadecimal format using ABC upto 12 places.

  3. I tried Integer.tohex, but it is out of range of integer

  4. In case of Double.tohex it gives 0x1.dc9ad4424da8p46

My friend is doing same job in ios using unsigned long long as datatype and 0x%02llx regular expression to convert nsstring

code is:

String x="131008130225002"; 
System.out.println(x);
    // System.out.println(Integer.parseInt(x));
     System.out.println(Double.parseDouble(x));
     System.out.println(Double.toHexString(Double.parseDouble(x)));
     String a1= toHex(x);
     System.out.println(a1);

toHex function:

static String toHex(String arg) {
    try {
        return String.format("%12x", new BigInteger(1, arg.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

Upvotes: 1

Views: 6056

Answers (2)

Bernhard Barker
Bernhard Barker

Reputation: 55649

It will fit in a long, so you can use Long.toHexString.

System.out.println(Long.toHexString(Long.parseLong("131008130225002")));

For a more generic solution, BigInteger also has a toString function which takes in a radix (16 being hex of course).

System.out.println(new BigInteger("131008130225002").toString(16));

Both of the above print out 7726b510936a.

Upvotes: 1

Yurii Shylov
Yurii Shylov

Reputation: 1217

String x = "131008130225002";
System.out.println(new BigInteger(x).toString(16));

The output is 7726b510936a.

Upvotes: 2

Related Questions