java對數據的位操作

以後搞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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章