Convert a byte array to a Hex string
来源:互联网 发布:中国房地产泡沫知乎 编辑:程序博客网 时间:2024/05/17 22:57
1. The simple way
public static String getHexString(byte[] b) throws Exception { String result = ""; for (int i=0; i < b.length; i++) { result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 ); } return result;}
2. A faster way
import java.io.UnsupportedEncodingException;public class StringUtils { static final byte[] HEX_CHAR_TABLE = { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f' }; public static String getHexString(byte[] raw) throws UnsupportedEncodingException { byte[] hex = new byte[2 * raw.length]; int index = 0; for (byte b : raw) { int v = b & 0xFF; hex[index++] = HEX_CHAR_TABLE[v >>> 4]; hex[index++] = HEX_CHAR_TABLE[v & 0xF]; } return new String(hex, "ASCII"); } public static void main(String args[]) throws Exception{ byte[] byteArray = { (byte)255, (byte)254, (byte)253, (byte)252, (byte)251, (byte)250 }; System.out.println(StringUtils.getHexString(byteArray)); /* * output : * fffefdfcfbfa */ }}
3.A more elegant (based on a suggestion by Lew on usenet-cljp)
static final String HEXES = "0123456789ABCDEF"; public static String getHex( byte [] raw ) { if ( raw == null ) { return null; } final StringBuilder hex = new StringBuilder( 2 * raw.length ); for ( final byte b : raw ) { hex.append(HEXES.charAt((b & 0xF0) >> 4)) .append(HEXES.charAt((b & 0x0F))); } return hex.toString(); }
- Convert a byte array to a Hex string
- convert a byte array to a hexadecimal string
- Convert a string to a byte array and vica-versa in C#
- How to display a byte array as hex values
- convert a hexadecimal string to a byte string
- Convert byte array to char* in a clr wrapper
- Swift: How to convert a String to UInt8 array?
- convert an int into a byte array
- convert a string to XmlElement
- Convert a String to a Number
- convert List<String> to a String
- How to convert a String to DateTime
- convert from to (byte [] array)
- insert a image to the database. (convert byte[] to varbinary)
- insert a image to the database(convert byte[] to binary)
- ASC Table, Convert String to Hex String
- Convert a string to an enum
- experiment : convert a string to crc32
- ip攻击 百度
- 重装win7后无法启动fedora
- C语言实现链队列
- 关于在IE下对Select标签设置innerHTML无效的问题
- oracle 一些优化设计原则
- Convert a byte array to a Hex string
- .Net开发人员常犯的6大安全错误
- 出现“Xcode could not find a valid private-key/...”一种解决办法
- flex的事件旅程
- java_colletction应用:从hashmap到array的转换
- 我的第一篇博客
- Oracle OCM 认证指南
- 2011-9-5多线程
- spring aop的一些局限性。