在一个二进制文件中有很多整形数字。
我写了半天,用这两个方法来读取二进制和double(float)类型
但是某些数字,它读出来的结果是错误的。class ByteReader{
private DataInputStream is;

public ByteReader(){}

public ByteReader(DataInputStream is)
{
this.is = is;
}

public void setDataInputStream(DataInputStream dis){
this.is = dis;
}

public int read4ByteIntger() throws IOException
{
byte[] bt = new byte[4];
is.read(bt, 0, bt.length);
return (bt[0]) | (bt[1]<<8 | bt[2]<<16 | bt[3]<<24);
}

public String read16ByteString() throws IOException
{
byte[] bt = new byte[16];
is.read(bt , 0, bt.length);
return new String(bt);
}

public float arr2float ( int start) throws IOException {
byte[] arr = new byte[4];
is.read(arr , 0 , arr.length);
int i = 0;
int len = 4;
int cnt = 0;
byte[] tmp = new byte[len];
for (i = start; i < (start + len); i++) {
tmp[cnt] = arr[i];
cnt++;
}
int accum = 0;
i = 0;
for ( int shiftBy = 0; shiftBy < 32; shiftBy += 8 ) {
accum |= ( (long)( tmp[i] & 0xff ) ) << shiftBy;
i++;
}
return Float.intBitsToFloat(accum);
}

public double arr2double  (int start) throws IOException {
byte[] arr = new byte[4];
is.read(arr , 0, arr.length);
int i = 0;
int len = 8;
int cnt = 0;
byte[] tmp = new byte[len];
for (i = start; i < (start + len); i++) {
tmp[cnt] = arr[i];
//System.out.println(java.lang.Byte.toString(arr[i]) + " " + i);
cnt++;
}
long accum = 0;
i = 0;
for ( int shiftBy = 0; shiftBy < 64; shiftBy += 8 ) {
accum |= ( (long)( tmp[i] & 0xff ) ) << shiftBy;
i++;
}
return Double.longBitsToDouble(accum);
}
}
double xxx = br.arr2float(0);
// double类型读取全部正确。int cur = br.read4ByteIntger();
//这个就不知道为什么不好说了。。br.read4ByteInteger 
当遇到
1 , 2 , 3,4,5,6,7,8,9 等数字的时候全部读取正确
但是
碰到 1001 后返回过来的结果是   
1001 -> 读取过来是 -23有人知道原因吗?

解决方案 »

  1.   

    return (bt[0]) | (bt[1]<<8 | bt[2]<<16 | bt[3]<<24);这个肯定不对拉,return = (int) ( ((bt[3]<<24 & 0xFF000000)) | ((bt[2]<<16 & 0xFF0000)) |
                         ((bt[1]<<8 & 0xFF00)) | (bt[0] & 0xFF));
    这个应该可以不过注意字节序.
    建议楼主用nio里的ByteBuffer
      

  2.   

    哇....
    thank you, 正常了~
      

  3.   

        public float arr2float ( int start) throws IOException {
            byte[] arr = new byte[4];
            is.read(arr , 0 , arr.length);      
            byte[] tmp = arr.clone();
            int accum = 0;
            int i = 0;
            for ( int shiftBy = 0; shiftBy < 32; shiftBy += 8 ) {
                accum |= (((int)tmp[i])&0x000000ff) << shiftBy;
                i++;
            }
            return Float.intBitsToFloat(accum);
        }
    还有编码的时候是不是反过来遍的,如果是shiftBy 是不是要反过来,
        public float arr2float ( int start) throws IOException {
            byte[] arr = new byte[4];
            is.read(arr , 0 , arr.length);      
            byte[] tmp = arr.clone();
            int accum = 0;
            int i = 0;
            for ( int shiftBy = 32; shiftBy > 0; shiftBy -= 8 ) {
                accum |= (((int)tmp[i])&0x000000ff) << shiftBy;
                i++;
            }
            return Float.intBitsToFloat(accum);
        }