* [字节转换]
*
* @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