java 字节转换工具-查看字节二进制,字节转字符串,字节转大小端数字

/**
     * 读取指定长度的字节转为字符串
     * @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();
    }

猜你喜欢

转载自blog.csdn.net/c5113620/article/details/81136286