美文网首页
十六进制编码解码,java

十六进制编码解码,java

作者: 猫般慵懒只想着蜷在窝里 | 来源:发表于2020-02-11 10:00 被阅读0次

    public class ByteHexMain {

        public static void main(String[] args) throws Exception {

            String source = "study hard and make progress everyday";

            System.out.println("source : "+source);

            String hexStr = bytes2HexStr(source.getBytes("utf8"));  //编码

            System.out.println("encode result : "+ hexStr);

            String rawSource = new String(hexStr2Bytes(hexStr),"utf8");  //解码

            System.out.println("decode result : "+rawSource);

        }

        //byte转为hex串

        static String bytes2HexStr(byte[] byteArr) {

            if (null == byteArr || byteArr.length < 1) return "";

            StringBuilder sb = new StringBuilder();

            for (byte t : byteArr) {

                if ((t & 0xF0) == 0) sb.append("0");

                sb.append(Integer.toHexString(t & 0xFF));  //t & 0xFF 操作是为去除Integer高位多余的符号位(java数据是用补码表示)

            }

            return sb.toString();

        }

        //hex串转为byte

        static byte[] hexStr2Bytes(String hexStr) {

            if (null == hexStr || hexStr.length() < 1) return null;

            int byteLen = hexStr.length() / 2;

            byte[] result = new byte[byteLen];

            char[] hexChar = hexStr.toCharArray();

            for(int i=0 ;i<byteLen;i++){

              result[i] = (byte)(Character.digit(hexChar[i*2],16)<<4 | Character.digit(hexChar[i*2+1],16));

            }

            return result;

        }

    }

    运行结果:

    source : study hard and make progress everyday

    encode result : 7374756479206861726420616e64206d616b652070726f6772657373206576657279646179

    decode result : study hard and make progress everyday

    ————————————————

    相关文章

      网友评论

          本文标题:十六进制编码解码,java

          本文链接:https://www.haomeiwen.com/subject/amvtfhtx.html