Hello, dear.

At the moment I use a subject of this type:

public static String toHexString(byte[] ba) { StringBuilder str = new StringBuilder(); for (int i = 0; i < ba.length; i++) { str.append(ba[i]<16?"0":"") .append(String.format("%x",ba[i]).toUpperCase()); } return str.toString().trim(); } 

I can not figure out why the result may be:

 00 00 0D 00 00 00 00 00 54 00 65 00 73 00 74 00 20 00 4D 00 65 00 73 00 73 00 61 00 67 00 65 00 00 00 0D2 04 00 00 

After all, D2 == 210 and clearly more than 16 ...

Tell me, please, what could be the reason, and I would also like to see the most correct, from your point of view, implementation of the subject. Thank!

  • Uff ... I apologize for the stupidity. It’s completely out of my head that the format can use something like “% 02x”. Question by mistake remains to improve the knowledge of the theory. The question about the best option also remains. I do not correct the text of the question. - Yevgeny Karpov
  • Maybe it will help: stackoverflow.com/q/923863/276994 Based on the answers, there is no "canonical" way. - VladD
  • one
    I read the stack on this topic ... But, you see, using BigIntedger for such conversion is the top of a programmer's genius. - Yevgeny Karpov

1 answer 1

I use this option:

 public static String bytesToHexString(byte[] array) { char[] val = new char[2*array.length]; String hex = "0123456789ABCDEF"; for (int i = 0; i < array.length; i++) { int b = array[i] & 0xff; val[2*i] = hex.charAt(b >>> 4); val[2*i + 1] = hex.charAt(b & 15); } return String.valueOf(val); } 

PS And String on bytes is completely simple ...

  • Did you see the link by the link 1 line? - Gorets
  • one
    I saw, but using the BigInteger or apache package does not seem like a good idea to me ... - Yevgeny Karpov
  • one
    1 line leading to a binary in megabytes is not very good ... - Barmaley