convert a byte array to a hexadecimal string
2015-04-07 18:34
411 查看
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(); }
相关文章推荐
- Convert a byte[] array to readable string format. This makes the "hex" readable!
- Convert a string to a byte array and vica-versa in C#
- Byte Array to Hexadecimal String
- convert a hexadecimal string to a byte string
- Java: convert a file to a byte array, then convert byte array to a file.
- Convert byte array to char* in a clr wrapper
- byte-array-to-string-transformer 作用
- how convert large HEX string to binary array ?
- string to byte array ----- byte array to string
- .net array convert to class String
- ByteArray to String过程中的编码问题
- How to convert array<System::Byte> to char* in C++ CLR?
- Convert int to byte array
- AS3 String to ByteArray,ByteArray to String
- Android Bitmap convert to ByteArray
- Convert Document to ByteArrayInputStream
- convert from to (byte [] array)
- Go string to ascii byte array
- Convert character array to string in MATLAB
- org.apache.shiro.codec.CodecException: Unable to convert source [hello] to byte array using encoding