How to convert a byte array to a hex string in Java?

后端 未结 27 3455
花落未央
花落未央 2020-11-21 04:19

I have a byte array filled with hex numbers and printing it the easy way is pretty pointless because there are many unprintable elements. What I need is the exact hexcode in

相关标签:
27条回答
  • 2020-11-21 04:55

    A Guava solution, for completeness:

    import com.google.common.io.BaseEncoding;
    ...
    byte[] bytes = "Hello world".getBytes(StandardCharsets.UTF_8);
    final String hex = BaseEncoding.base16().lowerCase().encode(bytes);
    

    Now hex is "48656c6c6f20776f726c64".

    0 讨论(0)
  • 2020-11-21 04:55

    I usually use the following method for debuf statement, but i don't know if it is the best way of doing it or not

    private static String digits = "0123456789abcdef";
    
    public static String toHex(byte[] data){
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i != data.length; i++)
        {
            int v = data[i] & 0xff;
            buf.append(digits.charAt(v >> 4));
            buf.append(digits.charAt(v & 0xf));
        }
        return buf.toString();
    }
    
    0 讨论(0)
  • 2020-11-21 04:57

    Here is a java.util.Base64-like implementation(partial), isn't it pretty?

    public class Base16/*a.k.a. Hex*/ {
        public static class Encoder{
            private static char[] toLowerHex={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
            private static char[] toUpperHex={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
            private boolean upper;
            public Encoder(boolean upper) {
                this.upper=upper;
            }
            public String encode(byte[] data){
                char[] value=new char[data.length*2];
                char[] toHex=upper?toUpperHex:toLowerHex;
                for(int i=0,j=0;i<data.length;i++){
                    int octet=data[i]&0xFF;
                    value[j++]=toHex[octet>>4];
                    value[j++]=toHex[octet&0xF];
                }
                return new String(value);
            }
            static final Encoder LOWER=new Encoder(false);
            static final Encoder UPPER=new Encoder(true);
        }
        public static Encoder getEncoder(){
            return Encoder.LOWER;
        }
        public static Encoder getUpperEncoder(){
            return Encoder.UPPER;
        }
        //...
    }
    
    0 讨论(0)
  • 2020-11-21 04:57
    private static String bytesToHexString(byte[] bytes, int length) {
            if (bytes == null || length == 0) return null;
    
            StringBuilder ret = new StringBuilder(2*length);
    
            for (int i = 0 ; i < length ; i++) {
                int b;
    
                b = 0x0f & (bytes[i] >> 4);
                ret.append("0123456789abcdef".charAt(b));
    
                b = 0x0f & bytes[i];
                ret.append("0123456789abcdef".charAt(b));
            }
    
            return ret.toString();
        }
    
    0 讨论(0)
  • 2020-11-21 04:58

    If you're looking for a byte array exactly like this for python, I have converted this Java implementation into python.

    class ByteArray:
    
    @classmethod
    def char(cls, args=[]):
        cls.hexArray = "0123456789ABCDEF".encode('utf-16')
        j = 0
        length = (cls.hexArray)
    
        if j < length:
            v = j & 0xFF
            hexChars = [None, None]
            hexChars[j * 2] = str( cls.hexArray) + str(v)
            hexChars[j * 2 + 1] = str(cls.hexArray) + str(v) + str(0x0F)
            # Use if you want...
            #hexChars.pop()
    
        return str(hexChars)
    
    array = ByteArray()
    print array.char(args=[])
    
    0 讨论(0)
  • 2020-11-21 04:59

    The method javax.xml.bind.DatatypeConverter.printHexBinary(), part of the Java Architecture for XML Binding (JAXB), was a convenient way to convert a byte[] to a hex string. The DatatypeConverter class also included many other useful data-manipulation methods.

    In Java 8 and earlier, JAXB was part of the Java standard library. It was deprecated with Java 9 and removed with Java 11, as part of an effort to move all Java EE packages into their own libraries. It's a long story. Now, javax.xml.bind doesn't exist, and if you want to use JAXB, which contains DatatypeConverter, you'll need to install the JAXB API and JAXB Runtime from Maven.

    Example usage:

    byte bytes[] = {(byte)0, (byte)0, (byte)134, (byte)0, (byte)61};
    String hex = javax.xml.bind.DatatypeConverter.printHexBinary(bytes);
    

    Will result in:

    000086003D
    

    This answer the same as this one.

    0 讨论(0)
提交回复
热议问题