package com.tcpip;
/**
* 在tcp/ip协议中以BigEndian方式的编码与解码
* @author
*
*/
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 BYTEMASK = 0xFF;
public static String byteArrayToDecimalString(byte[] bArray){
StringBuilder rtn = new StringBuilder();
for(byte b:bArray){
rtn.append(b&BYTEMASK).append(" ");
}
return rtn.toString();
}
/**
* 对val进行编码
* @param dst 源字节数组
* @param val 需要编码的long值
* @param offset 编码起始的偏移量
* @param size 编码的位数
* @return
*/
public static int encodeIntBigEndian(byte[] dst,long val,int offset,int size){
for(int i=0;i<size;i++){
dst[offset++] = (byte)(val >> ((size-i-1)*Byte.SIZE));
}
return offset;
}
/**
* 对字节数组val进行解码
* @param val 源字节数组
* @param offset 解码起始的偏移量
* @param size 解码的位数
* @return
*/
public static long decodeIntBigEndian(byte[] val,int offset,int size){
long rtn = 0;
for(int i=0;i<size;i++){
rtn = (rtn<<Byte.SIZE) | ((long)val[offset+i] & BYTEMASK);
}
return rtn;
}
public static void main(String args[]){
byte[] message= new byte[BSIZE];
int r = encodeIntBigEndian(message,1999999999,0,BSIZE);
System.out.println(r);
long rl = decodeIntBigEndian(message,0,BSIZE);
System.out.println(rl);
}
}
转载于:https://my.oschina.net/u/2552902/blog/543962