ByteUtil

import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ByteUtil {

    /**
     * 字符串转16进制
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || "".equals(hexString)) {
            return null;
        }
        // toUpperCase将字符串中的所有字符转换为大写
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        // toCharArray将此字符串转换为一个新的字符数组。
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * charToByte返回在指定字符的第一个发生的字符串中的索引,即返回匹配字符
     *
     * @param c
     * @return
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 将字节数组转换为16进制字符串
     *
     * @param bytes
     * @return
     */
    public static String binaryToHexString(byte[] bytes) {
        String hexStr = "0123456789ABCDEF";
        StringBuilder result = new StringBuilder();
        String hex = "";
        for (byte b : bytes) {
            hex = String.valueOf(hexStr.charAt((b & 0xF0) >> 4));
            hex += String.valueOf(hexStr.charAt(b & 0x0F));
            result.append(hex).append(" ");
        }
        return result.toString();
    }

    /**
     * 截取指定位置判断消息类型
     *
     * @param position
     * @param data
     * @return
     */
    public static String getFunctionCode(int[] position, String[] data) {
        StringBuilder builder = new StringBuilder("");
        for (int i : position) {
            try {
                builder.append(data[i]);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return builder.toString();
    }

    /**
     * Hex字符串转Byte
     *
     * @param hex 范围为0x00到0xFF
     * @return
     */
    public static byte hexToByte(String hex) {
        return (byte) Integer.parseInt(hex, 16);
    }

    /**
     * @param hex
     * @return
     */
    public static String hexToNumber(String hex) {
        hex = hex.replaceAll(" ", "");
        StringBuilder intString = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            String tem = hex.substring(i, i + 2);
            intString.append(Integer.parseInt(tem, 16));
        }
        return intString.toString();
    }

    /**
     * 16进制表示的字符串转换为字节数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll(" ", "");
        int len = hexString.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个字节
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return bytes;
    }

    /**
     * int转16进制字符串(两个字节)
     *
     * @param v
     * @return
     */
    public static String intToHexString(int v) {
        return String.format("%04x", v);
    }

    /**
     * int转16进制字符串(1个字节)
     *
     * @param v
     * @return
     */
    public static String intToHexStringSingle(int v) {
        return String.format("%02x", v);
    }

    /**
     * 16进制字符串转int(两个字节)
     *
     * @param hex
     * @return
     */
    public static int hexStringToInt(String hex) {
        return Integer.parseInt(hex.replaceAll(" ", ""), 16);
    }

    /**
     * 字符串转化成为16进制字符串
     *
     * @param s
     * @return
     */
    public static String strTo16(String s) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            int ch = s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str.append(s4);
        }
        return str.toString();
    }

    /**
     * 字节数组转16进制
     *
     * @param bytes 需要转换的byte数组
     * @return 转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() < 2) {
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 日期转换7个字节
     *
     * @param date
     * @return
     */
    public static byte[] dateToBytes(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy MM dd HH mm ss");
        String str = df.format(date);
        String[] strings = str.split(" ");
        String[] newStrings = new String[5];
        System.arraycopy(strings, 1, newStrings, 0, strings.length - 1);
        byte[] bytes = new byte[7];
        byte[] temByte = ByteUtil.hexStringToByteArray(ByteUtil.intToHexString(Integer.parseInt(strings[0])));
        bytes[0] = temByte[0];
        bytes[1] = temByte[1];
        int i = 2;
        for (String s : newStrings) {
            bytes[i] = ByteUtil.hexStringToByteArray(ByteUtil.intToHexStringSingle(Integer.parseInt(s)))[0];
            i++;
        }
        return bytes;
    }

    /**
     * 7个字节转日期
     *
     * @param hex
     * @return
     */
    public static Date hexToDate(String hex) {
        Date date = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

        StringBuilder sBuf = new StringBuilder();
        sBuf.append(Integer.parseInt(hex.substring(0, 4), 16));

        String str = hex.substring(4);
        for (int i = 0; i < str.length(); i = i + 2) {
            int num = Integer.parseInt(str.substring(i, i + 2), 16);
            sBuf.append(String.format("%02d", num));
        }
        try {
            date = df.parse(sBuf.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 产生numSize位16进制随机数
     *
     * @param numSize
     * @return
     */
    public static String getRandomValue(int numSize) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < numSize; i++) {
            char temp = 0;
            int key = (int) (Math.random() * 2);
            switch (key) {
                case 0:
                    //产生随机数字
                    temp = (char) (Math.random() * 10 + 48);
                    break;
                case 1:
                    //产生a-f
                    temp = (char) (Math.random() * 6 + 'a');
                    break;
                default:
                    break;
            }
            str.append(temp);
        }
        return str.toString();
    }

    public static void main(String[] args) {
        int v = 59466;
        byte[] byteArray = ByteUtil.hexStringToByteArray(ByteUtil.intToHexString(v));
        byte[] byteArray2 = Integer.toHexString(v).getBytes(StandardCharsets.UTF_8);

        System.out.println();
    }

 

posted on 2021-05-08 11:24  1zfang1  阅读(284)  评论(0编辑  收藏  举报

导航