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

后端 未结 27 3549
花落未央
花落未央 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: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>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;
        }
        //...
    }
    

提交回复
热议问题