以后搞JAVA了,发一些入门级没营养的东西。
数据位操作函数
数据位操作函数
/**整数转成byte数组*/
public static byte[] intToByteArray(int i) {
byte[] result = new byte[4];
result[0] = (byte) ((i >> 24) & 0xFF);
result[1] = (byte) ((i >> 16) & 0xFF);
result[2] = (byte) ((i >> 8) & 0xFF);
result[3] = (byte) (i & 0xFF);
return result;
}
/**短整型转到byte数组*/
public static byte[] shortToByteArray(short s)
{
byte[] shortBuf = new byte[2];
for(int i=0;i<=0;i++) {
int offset = (shortBuf.length - 1 -i)*8;
shortBuf[i] = (byte)((s>>>offset)&0xff);
}
return shortBuf;
}
/**byte转short,同时高低位互换*/
public static final int byteArrayToShort(byte [] b) {
return (b[1] << 8) + (b[0] & 0xFF);
}
/**byte转int,同时高低位互换*/
public static final int byteArrayToInt(byte [] b) {
return (b[3] << 24) + (b[2] << 16) + (b[1] << 8) + (b[0] & 0xFF);
}
/**整数转byte, 同时,高低位互换*/
public static byte[] intLtoH(int n){
byte[] b = new byte[4];
b[0] = (byte)(n & 0xff);
b[1] = (byte)(n >> 8 & 0xff);
b[2] = (byte)(n >> 16 & 0xff);
b[3] = (byte)(n >> 24 & 0xff);
return b;
}
/**将短整型高低位互换*/
public static byte[] shortLtoH(int n){
byte[] b = new byte[4];
b[0] = (byte)(n & 0xff);
b[1] = (byte)(n >> 8 & 0xff);
return b;
}
/**单字节转无符号整数*/
public static int bytesToInt(byte b)
{
return ((int)b >= 0) ? (int)b : 256 + (int)b;
}
/**
* 取得某一个data的第pos位的二进制位是0还是1
* @param data 要查的数据
* @param pos 第几位
* @return 0或1
*/
public static int getBin(int data,int pos)
{
pos-=1;
if(pos < 0)
return 0;
if(((1<<pos) & data )== 0)
return 0;
else
return 1;
}