Converting A String To Hexadecimal In Java

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

    Much better:

    public static String fromHexString(String hex, String sourceEncoding ) throws  IOException{
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buffer = new byte[512];
        int _start=0;
        for (int i = 0; i < hex.length(); i+=2) {
            buffer[_start++] = (byte)Integer.parseInt(hex.substring(i, i + 2), 16);
            if (_start >=buffer.length || i+2>=hex.length()) {
                bout.write(buffer);
                Arrays.fill(buffer, 0, buffer.length, (byte)0);
                _start  = 0;
            }
        }
    
        return  new String(bout.toByteArray(), sourceEncoding);
    }
    

提交回复
热议问题