java 解析C++二进制流

1、解析二进制流工具类


    public static void main(String[] args){
        //假设这是你要解析的二进制字节流
        byte[] bytes = new byte[];

        //声明一个 int[] 用于记录下标;
        int[] off = new int[] {0};

        //调用解析方法
        String data = getData(bytes,off,"int");

        System.out.println("解析结果" + data);
    }



    //bytes 代表要解析的byte数组,
    //start 代表截取的下标从什么开始,
    //fieldType 代表你要解析的类型,比如现在已有三种 int、double、char,想要解析别的类型可以再去网上找,查找的方法是,java解析shaor类型的c++二进制字节流
    public static String getData(byte[] bytes, int[] start, String fieldType){
        if(start[0] > bytes.length){
            System.out.println("超出")return "";
        }

        String result = "";
        byte[] bytes1 = new byte[0];

        if ("int".equalsIgnorecase(fieldType)|| "Integer".equalsIgnorecase(fieldType)) {

            bytes1 = splitByteArr(bytes,start,4);
            return String.valueof(byteArrayToInt(bytes1));
        
        } else if("double".equalsIgnorecase(fieldType)){

            bytes1=splitByteArr(bytes,start,8);
            return String.value0f(bytesToDouble(bytes1));
        }else if("char".equalsIgnorecase(fieldType)){

            bytes1 = splitByteArr(bytes,start,30);
            return  byteToStr(bytes1);
        }

        return;
    }
    
    //bytes 代表要解析的byte数组,start 代表截取的下标从什么开始,len 代表要解析的这个类型有多少字节
    public static byte[] splitByteArr(byte[] bytes, int[] start, int len){

        byte[] result = new byte[len];

        if(start[0] + len > bytes.length) {
            return result;
        }

        fon(int i = 0; i < len; i++) {
            result[il = bytes[start[0] + i];
        }

        start[0] += len;
        return result;
    }

    public static int byteArrayToInt(byte[] bytes){
        int value = 0;
        for(int i = 0; i< 4; i++) {

         value |= ((int)(bytes[i] & 0xff)) << (8 * 1);
         return value;

    }

    public static double bytesToDouble(byte[] bytes){
        long value = 0;
        for(int i = 0; i < 8; i++){
           value |= ((long) (data[i] & 0xff)) << (8 * 1);
        }
        double a =(double) Math.round(Double.longBitsToDouble(value) * 1000) / 1000;
       return Double.value0f(BigDecimal.value0f(a).setScale(5,BigDecimal.ROUND_HALF_up).toEngineeringString());
    }

    public static String byteToStr(byte[] bytes){
        Charset cs =Charset.forName("utf-8");

        ByteBuffer bb = ByteBuffer.allocate(bytes.length);
        bb.put(bytes);
        bb.flip();
        CharBuffer cb=cs.decode(bb);
        char[] array = cb.array();

        return new String(array);
    }


    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值