随笔-348  评论-598  文章-0  trackbacks-0
开发的时候发现,C#写入的字节顺序是从低到高(左低到右高),而Java的DataInputStream读取的数据是从高到低(左高到右低),所以当我们要用Java读取C#生成的二进制文件的时候,需要将DataInputStream里面的几个方法重写或者写一些辅助方法,例如下面两个函数是用来读取C#写入的无符号Short型和无符号长整型数据。 
/**
     * 逆转字节数组
     * 
     * 
@param b
     * 
@return
     
*/
    
private static byte[] reverse(byte[] b) {

        
byte[] temp = new byte[b.length];
        
for (int i = 0; i < b.length; i++) {
            temp[i] 
= b[b.length - 1 - i];
        }
        
return temp;
    }

    
/**
     * 读取无符号位的Short数,16位
     * 
     * 
@param readBuffer
     * 
@return
     * 
@throws IOException
     
*/
    
public static final BigInteger readUnsignedShort(byte[] readBuffer)
            
throws IOException {
        
if (readBuffer == null || readBuffer.length < 2)
            
return new BigInteger("0");
        
// 处理成无符号数
        byte[] uint64 = new byte[3];
        uint64[
2= 0;
        System.arraycopy(readBuffer, 
0, uint64, 02);
        
return new BigInteger(reverse(uint64));
    }

    
/**
     * 读取无符号位的长整数,64位
     * 
     * 
@param readBuffer
     * 
@return
     * 
@throws IOException
     
*/
    
public static final BigInteger readUnsignedInt64(byte[] readBuffer)
            
throws IOException {
        
if (readBuffer == null || readBuffer.length < 8)
            
return new BigInteger("0");
        
// 处理成无符号数
        byte[] uint64 = new byte[9];
        uint64[
8= 0;
        System.arraycopy(readBuffer, 
0, uint64, 08);
        
return new BigInteger(reverse(uint64));
    }


---------------------------------------------------------
专注移动开发

Android, Windows Mobile, iPhone, J2ME, BlackBerry, Symbian
posted on 2010-05-02 22:25 TiGERTiAN 阅读(3148) 评论(1)  编辑  收藏 所属分类: JavaDotNet

评论:
# re: C#的BinaryWriter和Java的DataInputStream之间的数据相互转换 2010-05-04 11:37 | 丽可酷
DataInputStream之间的数据相互转换   回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: