简体   繁体   中英

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;
}
String x = "131008130225002";
System.out.println(new BigInteger(x).toString(16));

The output is 7726b510936a.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM