Converting A String To Hexadecimal In Java

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

    check this solution for String to hex and hex to String vise-versa

    public class TestHexConversion {
    public static void main(String[] args) {
        try{
            String clearText = "testString For;0181;with.love";
            System.out.println("Clear Text  = " + clearText);
            char[] chars = clearText.toCharArray();
            StringBuffer hex = new StringBuffer();
            for (int i = 0; i < chars.length; i++) {
                hex.append(Integer.toHexString((int) chars[i]));
            }
            String hexText = hex.toString();
            System.out.println("Hex Text  = " + hexText);
            String decodedText = HexToString(hexText);
            System.out.println("Decoded Text = "+decodedText);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    
    public static String HexToString(String hex){
    
          StringBuilder finalString = new StringBuilder();
          StringBuilder tempString = new StringBuilder();
    
          for( int i=0; i

    Output as follows :

    Clear Text = testString For;0181;with.love

    Hex Text = 74657374537472696e6720466f723b303138313b776974682e6c6f7665

    Decoded Text = testString For;0181;with.love

提交回复
热议问题