/**
     * 读取指定长度的字节转为字符串
     * @param byteBuf  报文
     * @param from  包括的开始字节
     * @param to    包括的结束字节
     * @return
     */
    public static String getString(ByteBuf byteBuf,int from,int to)
    {
        StringBuilder stringBuilder = new StringBuilder();
        for(int i=from;i<to+1;i++)
        {
            if( (byteBuf.getByte(i) &0xFF)!=0){
                stringBuilder.append((char)byteBuf.getByte(i));
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 读取制定长度的字节转为数字
     * @param byteBuf  报文
     * @param from  包括的开始字节
     * @param to    包括的结束字节
     * @param fromRight  字节数据高位在数组末尾,大端格式
     * @return
     */
    public static int getLong(byte[] byteBuf,int from,int to,boolean fromRight)
    {
        int count=0;
        int data=0;
        if(fromRight){
            for(int i=from;i<to+1;i++)
            {
                data |=((byteBuf[i] & 0xFF) << (8*count));
                count++;
            }
        }else {
            for(int i=from;i<to+1;i++)
            {
                data |=((byteBuf[i] & 0xFF) << (8*((to-from)-count)));
                count++;
            }
        }
        return data;
    }

    /**
     * 字节转字符
     * @param byteBuf  报文
     * @param from  字节位置
     * @return
     */
    public static char getChar(ByteBuf byteBuf,int from)
    {
        return (char) (byteBuf.getByte(from) & 0xFF);
    }

    /**
     * 字节转二进制字符
     * @param byteBuf  报文
     * @param from
     * @param to
     * @return
     */
    public static String getBinary(ByteBuf byteBuf,int from,int to)
    {
        StringBuilder stringBuilder = new StringBuilder();
        for(int j=from;j<to+1;j++)
        {
            byte curr = byteBuf.getByte(j);
            for(int i=7;i>=0;i--){
                stringBuilder.append((byte)((curr>>i)&0x1));
            }
        }
        return stringBuilder.toString();
    }
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐