0

I converted a byte array into string by doing

String s = encryptedBytes1.toString();
String gh = convertStringToHex(s);

Then I printed on screen gh which is the hex form it returned this:

gh:[B@5985910 

this is the function convert

public static String convertStringToHex(String str){
    char[] chars = str.toCharArray();
    StringBuffer hex = new StringBuffer();
    for(int i = 0; i < chars.length; i++){
        hex.append(Integer.toHexString((int)chars[i]));
    }
    return hex.toString();
}

Can any one help me printing the hex form string?

papacito
  • 369
  • 7
  • 18

2 Answers2

2

In general you can convert string and hex values (numbers) with the following functions:

String hexString1 = "0x20";
Integer integer = Integer.decode(hexString); // is 32
String hexString1 = String.toHexString(integer); // is "20"

Now you need to iterate over your byteArray/String.

EDIT: As you specified your question, please see this answer on SO. I guess it is the same problem: Converting A String To Hexadecimal In Java

Community
  • 1
  • 1
Wintermute
  • 1,521
  • 1
  • 13
  • 34
0

encryptedBytes1.toString() is giving you a string representation of the object because all arrays are objects in Java it is not converting a byte array into a String.

I think that you are not converting your byte array to String properly. This works for me.

    byte encryptedBytes1[] = "ABCDEFGHIK".getBytes();
    String aux = new String(encryptedBytes1);
    System.out.println(convertStringToHex(aux));

41 42 43 44 45 46 47 48 49 4b

  • Keep in mind that you may need to specify a charset and that the primitive data byte takes 1 byte and char(which is meant to contain a Unicode Character) takes 2.
PbxMan
  • 7,525
  • 1
  • 36
  • 40