Java协议字节操作工具类详情

 更新时间:2022年09月07日 11:48:15   作者:何忆清风  
这篇文章主要介绍了Java协议字节操作工具类详情,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下

前言:

由于最近有解析协议的一些业务场景,需要用到一些字节操作工具,这里封装了一些比较常用的转换方法,测试后基本没有问题,可能一些比较偏门的数据会出现数据转换错误

  • int与数组相互转换
  • short与数组想换转换
  • 获取int指定位的数据
  • 获取int指定范围的位数据
  • 对象转换数组,数组转换对象
public class AppTest {
    /**
     * Rigorous Test :-)
     */
    @Test
    public void shouldAnswerWithTrue() {
        int hex = 16;
        System.out.println("获取16进制字符串数据:" + BitOperator.intToHexString(hex, 2));
        System.out.println("获取int类型0-8位的位数据:" + BitOperator.intNumberRightBitRangeOperator(999, 0, 8));
        System.out.println("获取int类型9-10位的位数据:" + BitOperator.intNumberRightBitRangeOperator(999, 8, 10));
        System.out.println("获取int类型10-12位的位数据:" + BitOperator.intNumberRightBitRangeOperator(256, 10, 12));
        short value = 256;
        System.out.println("获取short类型10-12位的位数据:" + BitOperator.shortNumberRightBitRangeOperator(value, 8, 12));

        //序列化与反序列化对象
        byte[] bytes = BitOperator.objToBytes(new A());
        A object = (A) BitOperator.bytesToObject(bytes);
        System.out.println(object);

        //转换int数据
        int intV = 12738123;
        byte[] bytes1 = {
            (byte) ((intV >> 24) & 0xff),
            (byte) ((intV >> 16) & 0xff),
            (byte) ((intV >> 8) & 0xff),
            (byte) (intV & 0xff)
        };

        byte[] bytes2 = BitOperator.intNumberToBytes(intV);
        int intNumber = BitOperator.bytesToIntNumber(bytes2);

        //转换short类型
        short sv = 999;
        byte[] bytes3 = {
            (byte) ((sv >> 8) & 0xff),
            (byte) (sv & 0xff)
        };
        short i = BitOperator.bytesToShortNumber(bytes3);
        System.out.println(i);
    }

    @ToString
    public static class A implements Serializable {
        public String name = "zs";

    }
}
@SuppressWarnings("all")
public class BitOperator {
    /** DIGITAL */
    public static final String DIGITAL = "0123456789ABCDEF";
    /** 16进制表示符 */
    public static final String HEX = "0x";
    /**
     * 数组转换成 int类型
     *
     * @param value value
     * @return the byte [ ]
     * @since 1.0
     */
    public static byte[] intNumberToBytes(int value) {
        return new byte[] {
            byteNumberRightBitRangeOperator(value, 24, 32),
            byteNumberRightBitRangeOperator(value, 16, 24),
            byteNumberRightBitRangeOperator(value, 8, 16),
            byteNumberRightBitRangeOperator(value, 0, 8)
        };
    }

    /**
     * Short number to bytes
     *
     * @param value value
     * @return the byte [ ]
     * @since 1.0
     */
    public static byte[] shortNumberToBytes(short value) {
        return new byte[] {
            (byte) shortNumberRightBitRangeOperator(value, 8, 16),
            (byte) shortNumberRightBitRangeOperator(value, 0, 8)
        };
    }

    /**
     * 数组转换成int数据
     *
     * @param bytes bytes
     * @return the int
     * @since 1.0
     */
    public static int bytesToIntNumber(byte[] bytes) {
        return bytesToNumberValue(bytes,0, (res, value) -> {
            return value | res;
        });
    }

    /**
     * 将数组转换成short类型
     *
     * @param bytes bytes
     * @return the int
     * @since 1.0
     */
    public static short bytesToShortNumber(byte[] bytes) {
        return bytesToNumberValue(bytes, (short) 0, (res, value) -> {
            return (short) (res | value);
        });
    }

    /**
     * Bytes to number value
     *
     * @param <T>      parameter
     * @param bytes    bytes
     * @param value    value
     * @param function function
     * @return the t
     * @since 1.0
     */
    public static <T extends Number> T bytesToNumberValue(byte[] bytes,
                                                          T value,
                                                          BiFunction<Integer, T, T> function) {
        try {
            int tmp = bytes.length * 8;
            for (int i = 0; i < bytes.length; i++) {
                tmp -= 8;
                value = function.apply(((bytes[i] & 0xff) << tmp), value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 16进制字符串转换为字节数组
     *
     * @param str str
     * @return the byte [ ]
     * @since 1.0
     */
    public static byte[] hexStringToByteArray(String str) {
        int len = str.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4)
                                  + Character.digit(str.charAt(i + 1), 16));
        }
        return data;
    }

    /**
     * 字节数组转换为16进制字符串
     *
     * @param src src
     * @return string string
     * @since 2022.1.1
     */
    public static String bytesArrayToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte b : src) {
            int v = b & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * 16进制字符串转换为字节数组
     *
     * @param hex hex
     * @return byte [ ]
     * @since 1.0
     */
    public static byte[] stringToBytes(String hex) {
        String hex1 = hex.replace(" ", "");
        char[] hex2char = hex1.toCharArray();
        byte[] bytes = new byte[hex1.length() / 2];
        byte temp;
        for (int p = 0; p < bytes.length; p++) {
            temp = (byte) (DIGITAL.indexOf(hex2char[2 * p]) * 16);
            temp += DIGITAL.indexOf(hex2char[2 * p + 1]);
            bytes[p] = (byte) (temp & 0xff);
        }
        return bytes;
    }

    /**
     * string字符串转换为 16进制字符串
     *
     * @param hex hex
     * @return the string
     * @since 1.0
     */
    public static String stringToHexString(String s) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str.append(s4);
        }
        return HEX + str.toString();
    }

    /**
     * int类型转换为16进制字符串
     *
     * @param value  value
     * @param number 不足指定位数补零
     * @return the string
     * @since 1.0
     */
    public static String intToHexString(int value, int number) {
        return numberValueToHexString(value, number, true);
    }

    /**
     * long类型转换为16进制字符串
     *
     * @param value  value
     * @param number number
     * @return the string
     * @since 1.0
     */
    public static String longToHexString(long value, int number) {
        return numberValueToHexString(value, number, true);
    }
    /**
     * 数字类型类型转换为16进制字符串
     *
     * @param value     value
     * @param number    number
     * @param isShowHex 是否拼接Ox
     * @return the string
     * @since 1.0
     */
    public static String numberValueToHexString(Object value, int number, boolean isShowHex) {
        if (number <= 0) {
            number = 2;
        }
        String hex = String.format("%0" + number + "x", value);
        return isShowHex ? HEX + hex : hex;
    }

    /**
     * 获取指定位的位数据
     *
     * @param value     value
     * @param bitNumber bit number
     * @return the int
     * @since 1.0
     */
    public static int intNumberRightBitOperator(int value, int bitNumber) {
        return bitNumberOperator(32, bitNumber, str -> str != null ? ((value & Integer.parseUnsignedInt(str, 2)) >> bitNumber)  : 0);
    }

    /**
     * 获取Long类型指定位数的数据
     *
     * @param value     value
     * @param bitNumber bit number
     * @return the int
     * @since 1.0
     */
    public static Long longNumberRightBitOperator(long value, int bitNumber) {
        return bitNumberOperator(64, bitNumber, str -> str != null ? ((value & Long.parseUnsignedLong(str, 2)) >> bitNumber)  : 0);
    }

    /**
     * 获取指定位的数据
     *
     * @param <T>      parameter
     * @param valueBit 数据类型的长度,例如int:32位
     * @param number   表示取多少位的数据
     * @param func     func
     * @return the int
     * @since 1.0
     */
    public static <T> T bitNumberOperator(int valueBit, int number, Function<String, T> func) {
        if (number > valueBit) {
            return (T) new Integer(0);
        }
        //获取到位的长度,根据长度生成对应的二进制位数据,获取数据需要生成 1
        StringBuilder builder = new StringBuilder();
        number = valueBit - number;
        for (int i = 0; i < valueBit; i++) {
            if (i == number) {
                builder.append("1");
            } else {
                builder.append("0");
            }
        }
        return func.apply(builder.toString());
    }
    /**
     * 获取int类型数据指定范围的数据
     *
     * @param value value
     * @param start start
     * @param end   end
     * @return the int
     * @since 1.0
     */
    public static int intNumberRightBitRangeOperator(int value, int start, int end) {
        return bitNumberRangeOperator(start, end, 32, str -> str != null ? ((value & Integer.parseUnsignedInt(str, 2)) >> start) : 0);
    }

    /**
     * 获取int类型数据指定范围的数据
     *
     * @param value value
     * @param start start
     * @param end   end
     * @return the int
     * @since 1.0
     */
    public static byte byteNumberRightBitRangeOperator(int value, int start, int end) {
        return (byte) intNumberRightBitRangeOperator(value, start, end);
    }

    /**
     * 获取short类型指定范围位数的数据
     *
     * @param value value
     * @param start start
     * @param end   end
     * @return the int
     * @since 1.0
     */
    public static short shortNumberRightBitRangeOperator(short value, int start, int end) {
        return bitNumberRangeOperator(start, end, 16, str -> (short) (str != null ? ((value  & Short.parseShort(str, 2)) >> start) : 0));
    }

    /**
     * 获取指定位的数据
     *
     * @param <T>        parameter
     * @param start      start
     * @param end        end
     * @param typeLength type length
     * @param func       func
     * @return the int
     * @since 1.0
     */
    public static <T> T bitNumberRangeOperator(int start, int end, int typeLength, Function<String, T> func) {
        if (start > end) {
            return (T) new Integer(0);
        }
        //获取到位的长度,根据长度生成对应的二进制位数据,获取数据需要生成 1
        StringBuilder builder = new StringBuilder();
        for (int i = typeLength - 1; i >= 0; i--) {
            if (i >= start && i < end) {
                builder.append("1");
            } else {
                builder.append("0");
            }
        }
        return func.apply(builder.toString());
    }


    /**
     * obj对象转换为字节数组
     *
     * @param obj obj
     * @return the string
     * @since 1.0
     */
    public static byte[] objToBytes(Object obj) {
        ByteArrayOutputStream objByteArray = new ByteArrayOutputStream();
        byte[] result;
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(objByteArray);) {
            objectOutputStream.writeObject(obj);
            objectOutputStream.flush();
            objectOutputStream.close();
            result = objByteArray.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("对象数据转换异常:" + e.getMessage());
        }
        return result;
    }

    /**
     * 反序列化对象
     *
     * @param bytes bytes
     * @return the object
     * @since 1.0
     */
    public static Object bytesToObject(byte[] bytes) {
        ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(bytes);
        Object result = null;
        try(ObjectInputStream objectInputStream = new ObjectInputStream(arrayInputStream);) {
            result = objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return result;
    }
}

到此这篇关于Java协议字节操作工具类详情的文章就介绍到这了,更多相关Java操作工具类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java WSDL接口webService实现方式

    java WSDL接口webService实现方式

    这篇文章主要为大家详细介绍了java WSDL接口webService实现方式的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04
  • Java多线程提交按照时间顺序获取线程结果详解流程

    Java多线程提交按照时间顺序获取线程结果详解流程

    在工作中是否存在这样的场景,多个线程提交执行,你不想全部线程执行结束了获取结果,而是有线程完成返回结果就获取消费。本文提供该场景的工具类,可以直接用哦
    2021-11-11
  • Tomcat数据源配置方法_JBuilder中

    Tomcat数据源配置方法_JBuilder中

    今天帮一同事配置一个数据源,采用tomcat5.5.9,本来是个很简单的事,以前也配过,但由于很长时间没用过容器提供的数据源了(IOC用惯了),也只记的个大概了,所以刚开始一配就出错了,google了一下,有很多资料,照着试试却都不好使(到不是别人说的不对,只是大家用的版本不同)。
    2008-10-10
  • Spring Boot中Elasticsearch的连接配置原理与使用详解

    Spring Boot中Elasticsearch的连接配置原理与使用详解

    在Spring Boot中,我们可以通过Elasticsearch实现对数据的搜索和分析,本文将介绍Spring Boot中Elasticsearch的连接配置、原理和使用方法,感兴趣的可以了解一下
    2023-09-09
  • 简单实现Spring的IOC原理详解

    简单实现Spring的IOC原理详解

    这篇文章主要介绍了简单实现Spring的IOC原理详解,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Java NIO实现聊天系统

    Java NIO实现聊天系统

    这篇文章主要为大家详细介绍了Java NIO实现聊天系统,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-11-11
  • Spring Boot 集成Mybatis实现主从(多数据源)分离方案示例

    Spring Boot 集成Mybatis实现主从(多数据源)分离方案示例

    本篇文章主要介绍了Spring Boot 集成Mybatis实现主从(多数据源)分离方案实例,具有一定的参考价值,有兴趣的可以了解一下。
    2017-03-03
  • Spring创建IOC容器的方式解析

    Spring创建IOC容器的方式解析

    这篇文章主要介绍了Spring创建IOC容器的方式解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • Spring数据库连接池实现原理深入刨析

    Spring数据库连接池实现原理深入刨析

    开发web项目,我们肯定会和数据库打交道,因此就会涉及到数据库链接的问题。在以前我们开发传统的SSM结构的项目时进行数据库链接都是通过JDBC进行数据链接,我们每和数据库打一次交道都需要先获取一次链接,操作完后再关闭链接,这样子效率很低,因此就出现了连接池
    2022-11-11
  • 6种SpringBoot中自定义starter的方式介绍

    6种SpringBoot中自定义starter的方式介绍

    在SpringBoot生态中,starter是一种特殊的依赖,它能够自动装配相关组件,简化项目配置,本文将详细介绍6种不同的自定义starter开发方法,有需要的可以了解下
    2025-04-04

最新评论