是连续的4个byte数组
我是以byte读取的,现在想将它们合并成一个int

解决方案 »

  1.   

    先用循环语句把byte读取到string 中,然后转换成int
      

  2.   

    int i;
    i = b[0];
    i += b[1]*256;
    i += b[2]*256*256;
    i += b[3]*256*256*256;这是高字节在前低字节在后的情况,如果要求低字节在前高字节在后则反之。
      

  3.   

    int i;
    i = b[0];
    i += b[1]*256;
    i += b[2]*256*256;
    i += b[3]*256*256*256;------------
    真罗嗦呀,写为:
    for(int a=0,i=0; i<4; i++){
      a = (a<<8)+b[3-i];
    }但这样是不行的,要考虑到byte是一个signed类型,最高位是符号位,低7位是数值,使用Integer(Byte)类的bit方法cast到int类型再相加才可以
      

  4.   

    你试试用asIntBuffer().put()这个函数,好像这个可以很简单地解决掉的。
      

  5.   

    String str="";
                 int i=0;
                 while(i<4)
                    {
                     str+=Integer.toString(buf[i]);//buf[i]是 byte的数组
                     i++;
                     }
                 int j=Integer.parseInt(str);
                 得出的j还是带符号的.存在负数
      

  6.   

    给你个参考程序,不过这里的是无符号的 public static int parseInt(byte[] b, int off, int len)
            throws NumberFormatException
        {
            int c;        if (b == null || len <= 0 || !isDigit(c = b[off++])) {
                throw new NumberFormatException();
            }        int n = c - '0';        while (--len > 0) {
                if (!isDigit(c = b[off++])) {
                    throw new NumberFormatException();
                }
                n = n * 10 + c - '0';
            }        return n;
        }
      

  7.   

    其实这样就行了
    for(int a=0,i=0; i<4; i++){
      int t = 0;
      t = (t^b[3-i]);
      a = (a<<8)+t;
    }用一个异或位操作就可以把符号也算作数值,你试一下
      

  8.   

    这是java的DataInputStream里的源代码:public final int readInt() throws IOException {
            int ch1 = in.read();
            int ch2 = in.read();
            int ch3 = in.read();
            int ch4 = in.read();
            if ((ch1 | ch2 | ch3 | ch4) < 0)
                throw new EOFException();
            return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
        }