Converting A String To Hexadecimal In Java

前端 未结 21 2606
青春惊慌失措
青春惊慌失措 2020-11-22 09:55

I am trying to convert a string like \"testing123\" into hexadecimal form in java. I am currently using BlueJ.

And to convert it back, is it the same thing except b

21条回答
  •  庸人自扰
    2020-11-22 10:40

    byte[] bytes = string.getBytes(CHARSET); // you didn't say what charset you wanted
    BigInteger bigInt = new BigInteger(bytes);
    String hexString = bigInt.toString(16); // 16 is the radix
    

    You could return hexString at this point, with the caveat that leading null-chars will be stripped, and the result will have an odd length if the first byte is less than 16. If you need to handle those cases, you can add some extra code to pad with 0s:

    StringBuilder sb = new StringBuilder();
    while ((sb.length() + hexString.length()) < (2 * bytes.length)) {
      sb.append("0");
    }
    sb.append(hexString);
    return sb.toString();
    

提交回复
热议问题