文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2024-04-02 19:55

关注

前言:

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

public class AppTest {
    
    @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 {
    
    public static final String DIGITAL = "0123456789ABCDEF";
    
    public static final String HEX = "0x";
    
    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)
        };
    }

    
    public static byte[] shortNumberToBytes(short value) {
        return new byte[] {
            (byte) shortNumberRightBitRangeOperator(value, 8, 16),
            (byte) shortNumberRightBitRangeOperator(value, 0, 8)
        };
    }

    
    public static int bytesToIntNumber(byte[] bytes) {
        return bytesToNumberValue(bytes,0, (res, value) -> {
            return value | res;
        });
    }

    
    public static short bytesToShortNumber(byte[] bytes) {
        return bytesToNumberValue(bytes, (short) 0, (res, value) -> {
            return (short) (res | value);
        });
    }

    
    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;
    }

    
    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;
    }

    
    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();
    }

    
    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;
    }

    
    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();
    }

    
    public static String intToHexString(int value, int number) {
        return numberValueToHexString(value, number, true);
    }

    
    public static String longToHexString(long value, int number) {
        return numberValueToHexString(value, number, true);
    }
    
    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;
    }

    
    public static int intNumberRightBitOperator(int value, int bitNumber) {
        return bitNumberOperator(32, bitNumber, str -> str != null ? ((value & Integer.parseUnsignedInt(str, 2)) >> bitNumber)  : 0);
    }

    
    public static Long longNumberRightBitOperator(long value, int bitNumber) {
        return bitNumberOperator(64, bitNumber, str -> str != null ? ((value & Long.parseUnsignedLong(str, 2)) >> bitNumber)  : 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());
    }
    
    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);
    }

    
    public static byte byteNumberRightBitRangeOperator(int value, int start, int end) {
        return (byte) intNumberRightBitRangeOperator(value, start, end);
    }

    
    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));
    }

    
    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());
    }


    
    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;
    }

    
    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操作工具类内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯