Is there a simpler way to convert a byte array to a 2-byte-size hexadecimal string?

Apache Commons-Codec has the Hex class, which will do what you need.

Apache Commons-Codec has the Hex class, which will do what you need: String hexString = Hex. EncodeHexString(bytes); By far the easiest method. Don't mess with binary operators, use the libraries to do the dirty work =).

Use at least StringBuilder#append() instead of stringA += stringB to improve performance and save memory. Public static String binaryToHexString(byte bytes) { StringBuilder hex = new StringBuilder(bytes. Length * 2); for (byte be : bytes) { be &= 0xff; if (b Append("0"); hex.

Append(Integer. ToHexString(b)); } return hex.toString(); }.

Public static String to2DigitsHex(final byte bytes) { final StringBuilder accum = new StringBuilder(bytes. Length * 2); for (byte be : bytes) { be &= 0xff; if (b Append(Integer. ToHexString(b); } return accum.toString(); } You're better off using an explicit StringBuilder of your own if this routine is going to be called a lot.

Private static String to2DigitsHex(byte bs) { String s = new BigInteger(bs). ToString(16); return s.length()%2==0? S : "0"+s; }.

You could use BigInteger for this. Example: (new BigInteger(1,bytes)). ToString(16) You will need to add an '0' at the beginning.

A more elegant solution (taken from here) is: BigInteger I = new BigInteger(1,bytes); System.out. Println(String. Format("%1$06X", i)); You need to know the number of bytes in advance in order to use the correct formatter.

That's indeed a nice oneliner (+1), but I've profiled it before, it's relatively slow and, above all, it doesn't prefix bytes I have successfully used this for generation of MD5 hashes. I can't say anything about the performance. – kgiannakakis Apr 15 '10 at 14:21.

I'm not taking any credit for this implementation as I saw it as part of a similar discussion and thought it was an elegant solution: private static final String HEXES = "0123456789ABCDEF"; public String toHexString(byte bytes) { final StringBuilder hex = new StringBuilder(2 * bytes. Length); for (final byte be : _bytes) { hex. Append(HEXES.

CharAt((b & 0xF0) >> 4)) . Append(HEXES. CharAt((b & 0x0F))); } return hex.toString(); }.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions