由于在java中所有的数据类型都是有符号的,但是在工作中与c进行通信是是无符号的,所以造成比如说java中int类型占4个字节,当服务器传过来的四个字节为无符号整型,这时就不能用int来表示了所以就要另想办法,而且需要把java中的类型转化为byte数组
1.java中的无符号short类型转化为byte数组
用于java中无法用有符号的short表示无符号short,所以用int表示无符号的short类型,接着我们开始循环2次取int类型的低8位存在targets数组中,这样就可以取出来要转化的数了
// short整型转为byte类型的数组
public static byte[] unsigned_short_2byte(int length) {
byte[] targets = new byte[2];
for (int i = 0; i < 2; i++) {
int offset = (targets.length - 1 - i) * 8;
targets[i] = (byte) ((length >>> offset) & 0xff);
return array;
}
}return targets;}
2.无符号整型转化为byte
// 无符号整型转化为字节数组
public static byte[] unsigned_int_2byte(long length) {
byte[] targets = new byte[4];
for (int i = 0; i < 4; i++) {
int offset = (targets.length - 1 - i) * 8;
targets[i] = (byte) ((length >>> offset) & 0xff);
}
return targets;
}
3、无符号byte类型转为数组
public static byte[] unsigned_char_2byte (char res) {
byte[] bytelen = new byte[1];
bytelen[0] = (byte) res;
return bytelen;
}
4判断byte类型的某一位是否为
public static byte[] getBooleanArray(byte b) {
byte[] array = new byte[8];
for (int i = 7; i >= 0; i--) {
array[i] = (byte) (b & 1);
b = (byte) (b >> 1);
}
return array;
}
这里传进一个byte类型的数,然后循环判断&1是否等于1,存入数组,然后将byte数组向右移1位,再次循环,最后返回的数组就是byte中8位的bit位
5、将long类型转化为byte数组
public static byte[] long_2byte(long length) {
byte[] targets = new byte[8];
for (int i = 0; i<8 4; i++) {
int offset = (targets.length - 1 - i) * 8;
targets[i] = (byte) ((length >>> offset) & 0xff);
}
return targets;
}
同1,循环8次
6、读取byte数组中2无符号short位转为int
// 读取2个字节转为无符号整型
public static int shortbyte2int(byte[] res) {
DataInputStream dataInputStream = new DataInputStream(
new ByteArrayInputStream(res));
int a = 0;
try {
a = dataInputStream.readUnsignedShort();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
这里直接就可以读取两个字节的数转化为int类型,很方便
7、读取一个无符号字节转为int
public static int byte2char(byte[] res) {
DataInputStream dataInputStream = new DataInputStream(new ByteArrayInputStream(res));
int a = 0;
try {
a = dataInputStream.readUnsignedByte();
} catch (IOException e) {
e.printStackTrace();
}
return a;
}
8.读取四个字节转为long类型
public static long unintbyte2long(byte[] res) {
int firstByte = 0;
int secondByte = 0;
int thirdByte = 0;
int fourthByte = 0;
int index = 0;
firstByte = (0x000000FF & ((int) res[index]));
secondByte = (0x000000FF & ((int) res[index + 1]));
thirdByte = (0x000000FF & ((int) res[index + 2]));
fourthByte = (0x000000FF & ((int) res[index + 3]));
index = index + 4;
return ((long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFL;
}