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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值