convert a byte array to a hexadecimal string

来源:互联网 发布:51自学网办公软件 编辑:程序博客网 时间:2024/05/18 01:48
 public static String ByteArrayToHexString(byte[] bytes) {     final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};     // Each byte has two hex characters (nibbles)     char[] hexChars = new char[bytes.length * 2];      int v;     for (int j = 0; j < bytes.length; j++) {         // Cast bytes[j] to int, treating as unsigned value         v = bytes[j] & 0xFF;          hexChars[j * 2] = hexArray[v >>> 4];          hexChars[j * 2 + 1] = hexArray[v & 0x0F];     }     return new String(hexChars); }

或者

/** * 二进制转十六进制 * 因为一个byte对应8位二进制,取值范围是-128~127 * 所以一个byte对应两个十六进制数字 *  * @param bytes * @return */public static String bytesToHex(byte[] bytes) {    StringBuffer md5str = new StringBuffer();    //把数组每一字节换成16进制连成md5字符串    int digital;    for (int i = 0; i < bytes.length; i++) {         digital = bytes[i];        if(digital < 0) {            digital += 256;        }        if(digital < 16){            md5str.append("0");        }        md5str.append(Integer.toHexString(digital));    }    return md5str.toString().toUpperCase();}
0 0
原创粉丝点击