Excelence by Experience
[ start | index | login ]
start > dev > java tips > Converting byte array to hex and back

Converting byte array to hex and back

Created by maz. Last edited by maz, one year and 175 days ago. Viewed 234 times. #2
[diff] [history] [edit] [rdf]
labels
attachments

How to convert a bytearray to a hex string and back

byte array -> Hex

(originaly found this on >>http://rgagnon.com/javadetails/java-0596.html and want to preserve this for my work):

public class HexUtil
{
  private static final byte[] hexalphabet = "0123456789ABCDEF".getBytes();
  public static String toHex( byte [] raw ) 
  {
    if ( raw == null )
      return null;

StringBuilder hex = new StringBuilder( 2 * raw.length ); for ( byte b : raw ) hex.append(hexalphabet[(b & 0xF0) >> 4]) .append(hexalphabet[(b & 0x0F)]);

return hex.toString(); } }

Hex-String -> byte array

public static byte[] fromHex(String s)
  {
    byte[] b = new byte[s.length() / 2];
    for (int i = 0, j=0; i < b.length; i++, j=i*2)
    b[i] = (byte) Integer.parseInt(s.substring(j, j + 2), 16);
      return b;
  }
no comments | post comment

< May 2012 >
SunMonTueWedThuFriSat
12345
6789101112
13141516171819
20212223242526
2728293031

Most Viewed



Logged in Users: (0)
… and 3 Guests.
Help
For hints about formatting text see snipsnap-help.

Powered by SnipSnap 1.0b3-uttoxeter

amazers.net | © 2010 All rights reserved by Maz Rashid