zoukankan      html  css  js  c++  java
  • JAVA byte数组转化为16进制字符串输出

    最简单的方法:

    利用javax.xml.bind包下的DatatypeConverter

    printHexBinary

    public static java.lang.String printHexBinary(byte[] val)

    Converts an array of bytes into a string.

    Parameters:
    val - An array of bytes
    Returns:
    A string containing a lexical representation of xsd:hexBinary
    Throws:
    IllegalArgumentException - if val is null.


    import javax.xml.bind.DatatypeConverter;
    import java.io.UnsupportedEncodingException;
    public class test {
        public static void main(String[] args) throws UnsupportedEncodingException{
     		//print hex string version of HELLO WORLD
    		byte[] helloBytes = "HELLO WORLD".getBytes();
    		String helloHex = DatatypeConverter.printHexBinary(helloBytes);
    		System.out.printf("Hello hex: 0x%s
    ", helloHex);
     
    		//convert hex-encoded string back to original string
    		byte[] decodedHex = DatatypeConverter.parseHexBinary(helloHex);
    		String decodedString = new String(decodedHex, "UTF-8");
    		System.out.printf("Hello decoded : %s
    ", decodedString);	
        }
    }


    或者使用stackoverflow提供的方法,貌似最快

    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    又或者使用java源码:

    D:JAVAjdk1.8.0_65srcjavaxxmlindDatatypeConverterImpl.java

    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
    
        public String printHexBinary(byte[] data) {
            StringBuilder r = new StringBuilder(data.length * 2);
            for (byte b : data) {
                r.append(hexCode[(b >> 4) & 0xF]);
                r.append(hexCode[(b & 0xF)]);
            }
            return r.toString();
        }



    Keep it simple!
    作者:N3verL4nd
    知识共享,欢迎转载。
  • 相关阅读:
    trie树
    单调队列
    网络流24题——试题库问题
    费用流的简单应用
    Manacher算法
    KMP算法
    网络流之最小费用最大流
    网络流之二分图匹配【转】
    网络流之最大流
    矩阵快速幂优化菲波那切数列
  • 原文地址:https://www.cnblogs.com/lgh1992314/p/6616250.html
Copyright © 2011-2022 走看看