Converting A String To Hexadecimal In Java

前端 未结 21 2266
青春惊慌失措
青春惊慌失措 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:41

    Using Multiple Peoples help from multiple Threads..

    I know this has been answered, but i would like to give a full encode & decode method for any others in my same situation..

    Here's my Encoding & Decoding methods..

    // Global Charset Encoding
    public static Charset encodingType = StandardCharsets.UTF_8;
    
    // Text To Hex
    public static String textToHex(String text)
    {
        byte[] buf = null;
        buf = text.getBytes(encodingType);
        char[] HEX_CHARS = "0123456789abcdef".toCharArray();
        char[] chars = new char[2 * buf.length];
        for (int i = 0; i < buf.length; ++i)
        {
            chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
            chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
        }
        return new String(chars);
    }
    
    // Hex To Text
    public static String hexToText(String hex)
    {
        int l = hex.length();
        byte[] data = new byte[l / 2];
        for (int i = 0; i < l; i += 2)
        {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                + Character.digit(hex.charAt(i + 1), 16));
        }
        String st = new String(data, encodingType);
        return st;
    }
    
    0 讨论(0)
  • 2020-11-22 10:42

    To ensure that the hex is always 40 characters long, the BigInteger has to be positive:

    public String toHex(String arg) {
      return String.format("%x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
    }
    
    0 讨论(0)
  • 2020-11-22 10:43
    new BigInteger(1, myString.getBytes(/*YOUR_CHARSET?*/)).toString(16)
    
    0 讨论(0)
提交回复
热议问题