tcp通信解析工具类

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @author yousili
 * @since 2021/9/23
 */
public class BytesHelper {

    /**
     * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序。
     *
     * @param ary    byte数组
     * @param offset 从数组的第offset位开始
     * @return int数值
     */
    public static int bytesToInt(byte[] ary, int offset) {
        int value;
        value = (int) ((ary[offset] & 0xFF)
                | ((ary[offset + 1] << 8) & 0xFF00)
                | ((ary[offset + 2] << 16) & 0xFF0000)
                | ((ary[offset + 3] << 24) & 0xFF000000));
        return value;
    }

    /**
     * byte数组转16进制字符串
     *
     * @param messageDigest
     * @return
     */
    public static String toHexValue(byte[] messageDigest) {
        if (messageDigest == null) return "";
        StringBuilder hexValue = new StringBuilder();
        for (byte aMessageDigest : messageDigest) {
            // 同256 进行与操作   byte 0~128~-127(256) 范围 刚好是16进制的 0xFF
            // 如果不进行与操作    byte的-1 转成 int类型时会变成 0xFFFFFFFF
            int val = 0xFF & aMessageDigest;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 把byte转为字符串的bit
     */
    public static String byteToBit(byte b) {
        return ""
                + (byte) ((b >> 7) & 0x1) + (byte) ((b >> 6) & 0x1)
                + (byte) ((b >> 5) & 0x1) + (byte) ((b >> 4) & 0x1)
                + (byte) ((b >> 3) & 0x1) + (byte) ((b >> 2) & 0x1)
                + (byte) ((b >> 1) & 0x1) + (byte) ((b >> 0) & 0x1);
    }

    /**
     * 将byte转换为一个长度为8的byte数组,数组每个值代表bit
     */
    public static byte[] getBooleanArray(byte b) {
        byte[] array = new byte[8];
        for (int i = 7; i >= 0; i--) {
            array[i] = (byte) (b & 1);
            b = (byte) (b >> 1);
        }
        return array;
    }

    /**
     * 将字节转换成16进制字符串
     */
    public static String toHexString(byte buf) {
        String str = Integer.toHexString(buf);
        if (str.length() > 2) {
            str = str.substring(str.length() - 2);
        } else if (str.length() < 2) {
            str = "0" + str;
        }
        return "0x" + str.toUpperCase();
    }

    /**
     * 将16进制字符串转换成字节
     *
     * @param hex
     * @return
     */
    public static byte hexStrToByte(String hex) {
        String replace = hex.replace("0x", "");
        return (byte) Integer.parseInt(replace, 16);
    }

    /**
     * 获取byte的指定位的bit值, 大端模式
     * eg:b=2,i=0时 返回结果为0
     *
     * @param b b为传入的字节
     * @param i i为第几位(范围0-7,0为最低位),如要获取bit0,则i=0
     * @return
     */
    //
    public static byte getBit(byte b, int i) {
        byte bit = (byte) ((b >> i) & 0x1);
        return bit;
    }

    /**
     * byte数组(length=4)与 int 的相互转换; 数组b下标:0->3依次从地位到高位;
     * 例如:传入new byte[]{(byte) 255,0,0,0})输出结果为255
     *
     * @param b byte数组(length=4)
     * @return int
     */
    public static int byteArrayToInt(byte[] b) {
        return b[0] & 0xFF |
                (b[1] & 0xFF) << 8 |
                (b[2] & 0xFF) << 16 |
                (b[3] & 0xFF) << 24;
    }

    /**
     * Byte数组根据acssi码转成字符串
     *
     * @param b
     * @return
     */
    public static String byteArrayToAsciiStr(byte[] b) {
        String s = new String(b, StandardCharsets.US_ASCII);
        return s;
    }

    /**
     * byte[] 数组转为 long数值
     *
     * @param arr   数组
     * @param isBig 是否大端模式
     * @return
     */
    public static Long byteArrToLong(byte[] arr, boolean isBig) {
        return byteArrToNumber(arr, isBig, 8).longValue();
    }

    /**
     * byte[] 数组转为 long数值
     *
     * @param arr   数组
     * @param isBig 是否大端模式
     * @return
     */
    public static Integer byteArrToInt(byte[] arr, boolean isBig) {
        return byteArrToNumber(arr, isBig, 4).intValue();
    }


    /**
     * byte 转为一个数值
     *
     * @param arr
     * @param isBig 是否
     * @param trim  长度 long=8, int=4, short=2
     * @return
     */
    private static Number byteArrToNumber(byte[] arr, boolean isBig, int trim) {

        if (arr == null || arr.length == 0) {
            return null;
        }

        // 舍弃掉数组长度超过8的部分
        if (arr.length > trim) {

            for (int i = trim; i < arr.length; i++) {
                arr[i] = 0;
            }
        }
        long total = 0;
        for (int i = 0; i < arr.length; i++) {

            long arrVal = arr[i] & 0xFF;
            arrVal = isBig ? arrVal << ((arr.length - i - 1) * 8) : arrVal << ((i) * 8);
            total |= arrVal;
        }


        return total;
    }

    /**
     * 数据生成异或运算和结果
     *
     * @param datas 数据数组
     * @return 异或运算和结果
     */
    public static byte getXor(byte[] datas) {

        byte temp = datas[0];

        for (int i = 1; i < datas.length; i++) {
            temp ^= datas[i];
        }

        return temp;
    }

    /**
     * [from,to)数据生成异或运算和结果,无需数组拷贝
     *
     * @param datas 数据数组
     * @return 异或运算和结果
     */
    public static byte getXor(byte[] datas, int from, int to) {

        byte temp = datas[from];

        for (int i = from; i < to - 1; ) {
            temp ^= datas[++i];
        }

        return temp;
    }

    /**
     * 大端模式,short类型转成长度为2的byte数组
     *
     * @param n
     * @return
     */
    public static byte[] shortToBytes(short n) {
        byte[] b = new byte[2];

        b[1] = (byte) (n & 0xff);

        b[0] = (byte) ((n >> 8) & 0xff);

        return b;

    }

    /**
     * 大端模式 高字节在前,int转4位字节数组
     *
     * @param n
     * @return
     */
    public static byte[] intToBytes(int n) {
        byte[] b = new byte[4];
        b[3] = (byte) (n & 0xff);
        b[2] = (byte) (n >> 8 & 0xff);
        b[1] = (byte) (n >> 16 & 0xff);
        b[0] = (byte) (n >> 24 & 0xff);
        return b;
    }

    /**
     * 将int转换成字节数组并将数组数据添加到data中的从from下标开始处
     *
     * @param n    待转换的int
     * @param data 数组存放处
     * @param from 将转换后的数组按顺序添加到data中,从from下标开始(包含from)
     */
    public static void intToBytesWriteData(int n, byte[] data, int from) {
        data[from++] = (byte) (n & 0xff);
        data[from++] = (byte) (n >> 8 & 0xff);
        data[from++] = (byte) (n >> 16 & 0xff);
        data[from++] = (byte) (n >> 24 & 0xff);
    }

    /**
     * 将short转换成字节数组并将数组数据添加到data中的从from下标开始处
     *
     * @param n    待转换的int
     * @param data 数组存放处
     * @param from 将转换后的数组按顺序添加到data中,从from下标开始(包含from)
     */
    public static void shortToBytesWriteData(short n, byte[] data, int from) {
        data[from++] = (byte) (n & 0xff);
        data[from++] = (byte) (n >> 8 & 0xff);
    }

    /**
     * bit字符串转成byte
     *
     * @param bit bit字符串;长度只能为4或8
     * @return
     */
    public static byte bitToByte(String bit) {
        int re, len;
        if (null == bit) {
            return 0;
        }
        len = bit.length();
        if (len != 4 && len != 8) {
            return 0;
        }
        if (len == 8) {// 8 bit处理
            if (bit.charAt(0) == '0') {// 正数
                re = Integer.parseInt(bit, 2);
            } else {// 负数
                re = Integer.parseInt(bit, 2) - 256;
            }
        } else {//4 bit处理
            re = Integer.parseInt(bit, 2);
        }
        return (byte) re;
    }

    /**
     * 字符数组转成byte,BIT0对应的时chars数组最后一位
     *
     * @param bits bit字符串;长度只能为4或8
     * @return
     */
    public static byte bitToByte(char[] bits) {
        return bitToByte(new String(bits));
    }


    /**
     * 将长度为二的字节数组转为short
     *
     * @param b 长度为2
     * @return short
     */
    public static short bytesToShort(byte[] b) {
        return (short) (b[1] & 0xff | (b[0] & 0xff) << 8);
    }

    /**
     * 将数组从偏移量开始取两个字节转成short
     *
     * @param b    字节数组
     * @param from 偏移量
     * @return short
     */
    public static short bytesToShort(byte[] b, int from) {
        return (short) (b[from] & 0xff | (b[from + 1] & 0xff) << 8);
    }
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值