zoukankan      html  css  js  c++  java
  • 二进制数与十六进制数之间如何互相转换

    package com.demo;
    
    /**
     * 进制转换
     * @Author: zhouhe
     * @Date: 2019/7/18 12:00
     */
    public class HexUtil {
        /**
         * 二进制byte数组转十六进制byte数组
         * byte array to hex
         *
         * @param b byte array
         * @return hex string
         */
        public static String byte2hex(byte[] b) {
            StringBuilder hs = new StringBuilder();
            String stmp;
            for (int i = 0; i < b.length; i++) {
                stmp = Integer.toHexString(b[i] & 0xFF).toUpperCase();
                if (stmp.length() == 1) {
                    hs.append("0").append(stmp);
                } else {
                    hs.append(stmp);
                }
            }
            return hs.toString();
        }
    
        /**
         * 十六进制byte数组转二进制byte数组
         * hex to byte array
         *
         * @param hex hex string
         * @return byte array
         */
        public static byte[] hex2byte(String hex)
                throws IllegalArgumentException{
            if (hex.length() % 2 != 0) {
                throw new IllegalArgumentException ("invalid hex string");
            }
            char[] arr = hex.toCharArray();
            byte[] b = new byte[hex.length() / 2];
            for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
                String swap = "" + arr[i++] + arr[i];
                int byteint = Integer.parseInt(swap, 16) & 0xFF;
                b[j] = new Integer(byteint).byteValue();
            }
            return b;
        }
    
        public static void main(String[] args) {
            String str1 = "abcedefghijklmnopqrstuvwxyz";
            //String str1 = "1";
            String hexStr = HexUtil.byte2hex(str1.getBytes());
            System.out.println(hexStr);
            String str2 = new String(HexUtil.hex2byte(hexStr));
            System.out.println(str2);
            System.out.println(str1.equals(str2));
        }
    }
  • 相关阅读:
    8.池化内存分配
    7.netty内存管理-ByteBuf
    6.ChannelPipeline
    5.接入客户端连接
    4.Netty执行IO事件和非IO任务
    3.NioEventLoop的启动和执行
    2.NioEventLoop的创建
    1.netty服务端的创建
    微信订阅号开发初探
    jmeter自动化脚本编写
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/11207068.html
Copyright © 2011-2022 走看看