int2byte

/**
 * [字节转换]
 * 
 * @author zengdengyi
 * @version 1.0
 * @date 2015-1-12 下午1:20:27
 * 
 **/


public class ByteHelper {


/**
* @author zengdengyi
* @param res
* @return 高位在前
* @date 2015-1-12 下午1:20:58
*/
public static byte[] int2byte(int res) {
byte[] targets = new byte[4];


targets[3] = (byte) (res & 0xff);// 最低位
targets[2] = (byte) ((res >> 8) & 0xff);// 次低位
targets[1] = (byte) ((res >> 16) & 0xff);// 次高位
targets[0] = (byte) (res >>> 24);// 最高位,无符号右移。
return targets;
}


/**
* @author zengdengyi
* @param res
* @return 高位在前
* @date 2015-1-12 下午1:21:01
*/
public static int byte2int(byte[] res) {
int x = (res[3] & 0xff) | ((res[2] << 8) & 0xff00) // | 表示安位或
| ((res[1] << 24) >>> 8) | (res[0] << 24);
return x;
}


/**
* @author zengdengyi
* @param res
* @return 高位在前 len 2
* @date 2015-1-12 下午1:20:58
*/
public static byte[] int2byte2(int res) {
byte[] targets = new byte[2];
targets[1] = (byte) (res & 0xff);// 最低位
targets[0] = (byte) ((res >> 8) & 0xff);// 次低位
return targets;
}


/**
* @author zengdengyi
* @param res
* @return 高位在前 len =
* @date 2015-1-12 下午1:21:01
*/
public static int byte2int2(byte[] res) {
int x = (res[1] & 0xff) | ((res[0] << 8) & 0xff00); // | 表示安位或
return x;
}

}


//取byte 的bits
byte cmd_id = 15;
byte ack = 1;
byte type = 3;


byte flags = (byte) (type << 6 | ack << 5 | cmd_id);


System.out.println(flags + " ");
System.out.println(Integer.toBinaryString(flags));


int tmpFlags = (flags & 0xff);// 有符号byte 转为int
byte xx76 = (byte) (tmpFlags >> 6);
byte x5 = (byte) ((tmpFlags >> 5) & 0x01);
byte x4 = (byte) ((tmpFlags >> 4) & 0x01);
byte x3 = (byte) (flags & 0x0f);
System.out.println(" " + xx76 + " " + x5 + " " + x4 + " " + x3);


byte tts[] = new byte[8];
for (int i = 7; i >= 0; i--) {
tts[i] = (byte) (flags & 1);
flags = (byte) (flags >> 1);
}
for (int i = 0; i < tts.length; i++) {
System.out.println(tts[i]);
}



byte cmd_id = 15;
byte ack = 1;
byte type = 3;


byte flags = (byte) (type << 6 | ack << 5 | cmd_id);


System.out.println(flags + " ");
System.out.println(Integer.toBinaryString(flags));


int tmpFlags = (flags & 0xff);// 有符号byte 转为int
byte xx76 = (byte) (tmpFlags >> 6);
byte x5 = (byte) ((tmpFlags >> 5) & 0x01);
byte x4 = (byte) ((tmpFlags >> 4) & 0x01);
byte x3 = (byte) (flags & 0x0f);
System.out.println(" " + xx76 + " " + x5 + " " + x4 + " " + x3);


byte tts[] = new byte[8];
for (int i = 7; i >= 0; i--) {
tts[i] = (byte) (flags & 1);
flags = (byte) (flags >> 1);
}
for (int i = 0; i < tts.length; i++) {
System.out.println(tts[i]);
}


//取byte 的bits

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值