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)请问怎么转?

解决方案 »

  1.   

    首先34222已经超出short的区间,其次你的byte数组中高8位的起始值是1,所以转换出的short肯定是负数。
    如果想实现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;
        }
      

  2.   

    short.MAX_VALUE才只有32767
    你怎么让他表示34222 ,当然会越界了
      

  3.   

    想到了一个简单的办法:byte[] be=new byte[1];
    be[0]=(byte) 174; //174-256
    System.out.println(be[0]);
    那么我用-31314 +32768+32768=34222  这样可以得到正确的答案,这样可行性吗?
      

  4.   

    答:我想到了更简单的方法。就是说:JAVA short 的 -31314 与C语言中无符号的short值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
      

  5.   

    这个问题不复杂,是你自己搞复杂了,呵呵。首先34222不可能表示成一个short型的数。超出范围了。但是可以用int型的数来表示,而且一旦你用int型的数来表示,就不存在所谓的最高位是1的问题了。其实做法很简单,就是把你这个字符数组复制到长度为4的字符数组中,在输出为int型就可以了。
    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); 
        }
    }