Java的TCP/IP编程学习--简单的位操作编码

一、编码思想

对基本类型进行编码,encodeIntBigEndian()编码基本数据类型,decodeIntBigEndian()解码基本数据类型。

package main;

/**
 * @ClassName BruteForceCoding
 * @Description TODO
 * @Author Cays
 * @Date 2019/3/16 10:45
 * @Version 1.0
 **/
public class BruteForceCoding {
    private static byte byteVal=101;
    //数据项编码
    private static short shortVal=10001;
    private static int intVal=100000001;
    private static long longVal=1000000000001L;
    private final static int BSIZE=Byte.SIZE;
    //基本整数所占字节数
    private final static int SSIZE=Short.SIZE;
    private final static int ISIZE=Integer.SIZE;
    private final static int LSIZE=Long.SIZE;
    private final static int BYTEMAX=0xff;
    //8 bits
    public static String byteArrayToDecimalString(byte []bArray){
        StringBuilder rtn=new StringBuilder();
        for (byte b:bArray){
            rtn.append(b&BYTEMAX).append(" ");
        }//每一个字节作为一个无符号十进制打印出来
        return rtn.toString();
    }
    /*
     * Warning: Untested preconditions(0<=size<=8)
     */
    public static int encodeIntBigEndian(byte[] dst,long val,int offset,int size){
        //将数值向右移动,以使需要的字节处在该数值的低8位
        for (int i=0;i<size;i++){
            //最高位字节放在字节数组下标的最低位置,模拟大端存放方式
            dst[offset++]=(byte)(val>>((size-i-1)*Byte.SIZE));
        }
        //返回字节数组偏移量
        return offset;
    }
    public static long decodeIntBigEndian(byte[] val,int offset,int size){
        long rtn=0;
        for (int i=0;i<size;i++){
            //数组的低下标的字节放在long的高字节,
            //每次取一个字节,rtn左移8位,最低位与取数组的字节或,
            //即加入到rtn的最低位字节
            rtn=(rtn<<Byte.SIZE)|((long)val[offset+i]&BYTEMAX);
        }
        return rtn;
    }

    public static void main(String[] args) {
        //准备接收整数的数组
        byte[] message=new byte[BSIZE+SSIZE+ISIZE+LSIZE];
        //对每一项进行编码
        int offset=encodeIntBigEndian(message,byteVal,0,BSIZE);
        offset=encodeIntBigEndian(message,shortVal,offset,SSIZE);
        offset=encodeIntBigEndian(message,intVal,offset,ISIZE);
        encodeIntBigEndian(message,longVal,offset,LSIZE);
        //打印编码后的内容
        System.out.println("Encoded message:"+byteArrayToDecimalString(message));
        //decode several fields
        //对编码的数组中的某些字段进行解码
        long value=decodeIntBigEndian(message,BSIZE,SSIZE);
        System.out.println("Decoded short = "+value);
        value=decodeIntBigEndian(message,BSIZE+SSIZE+ISIZE,LSIZE);
        System.out.println("Decoded long = "+value);
        //
        offset=4;
        value=decodeIntBigEndian(message,offset,BSIZE);
        System.out.println("Decoded value (offset "+offset+" , size "+BSIZE
            +") = "+value);
        byte bVal=(byte)decodeIntBigEndian(message,offset,BSIZE);
        System.out.println("Same value as byte = "+ bVal);
    }
}

二、结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39400984/article/details/88696930