public static short ByteArraytoShort(byte[] b) {
short iOutcome = 0;
byte bLoop;
for (int i = 0; i < 2; i++) {
bLoop = b[i];
iOutcome += (bLoop & 0xff) << (8 * i);
}
return iOutcome;
}
public static void main(String[] args) throws Exception {
byte[] b = new byte[2];
b[0] = -82;
b[1] = -123;
short len = ByteArraytoShort(b);
System.out.println("负数的数据长度:" + len);
}得到的数据长度是:-31314
我想要得到的数据长度是: 34222 二进制:10000101(133) 10101110(174)请问怎么转?
如果想实现byte[1]作为高八位,byte[0]作为第八位转换,可以这样写: public static short ByteArraytoShort(byte[] b) {
short iOutcome = 0;
byte bLoop;
for (int i = 0; i < 2; i++) {
bLoop = b[i];
iOutcome |= (bLoop & 0xff) << (8 * i);
}
return iOutcome;
}
你怎么让他表示34222 ,当然会越界了
be[0]=(byte) 174; //174-256
System.out.println(be[0]);
那么我用-31314 +32768+32768=34222 这样可以得到正确的答案,这样可行性吗?
因此:在JAVA中要使用无符号的short,你直接使用java中的char就可以了(用它进行无符号short的大小比较等)。
当用System.out.println()输出时,由于char不会打出值,只会打出字符,因而当输出时,你简单转换类型就行了:
以你的1楼代码为例,byte[] b = new byte[2];
b[0] = -82;
b[1] = -123;
short len = ByteArraytoShort(b);
System.out.println("负数的数据长度:" + (int)(char)len); 运行结果:
负数的数据长度:34222
public class NegativeByteArrayToShort {
public static int ByteArraytoInt(byte[] b) {
int iOutcome = 0;
byte bLoop;
for (int i = 0; i < b.length; i++) {
bLoop = b[i];
iOutcome += (bLoop & 0xff) << (8 * i);
}
return iOutcome;
}
public static void main(String[] args) throws Exception {
byte[] b = new byte[4];
b[0] = -82;
b[1] = -123;
byte[] temp = new byte[4];
System.arraycopy(b, 0, temp, 0, 2); //复制到长度为4的字符数组中
int len = ByteArraytoInt(temp);
System.out.println("负数的数据长度:" + len);
}
}