“Char Array”对int:C ++ vs Java

时间:2015-02-10 03:12:38

标签: java c++

C ++中有一些代码如下:

struct Chunk
{
    int flag;
    int size;
};
Chunk chunk;
chunk.flag = 'DIVA';
chunk.size = 512;

然后写入文件(fp是文件的指针):

fwrite(&chunk, sizeof(chunk), 1, fp);

在Java中,要读取块,我需要这样做

// Read file
byte[] fileBytes = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(fileBytes);
fis.close();

byte[] flag = new byte[4];
byte[] size = new byte[4];
//LITTLE_ENDIAN : reverse it
System.arraycopy(fileBytes, 0, flag, 0, flag.length);
System.arraycopy(fileBytes, flag.length, size, 0, size.length);

ArrayUtils.reverse(flag);
ArrayUtils.reverse(size);

然后,检查结果

if(Arrays.equals(flag, "DIVA".getBytes()))
{
// do sth.
}

或者在java中这样做('Bytes.toInt'来自HBase)

int flag;
int size;
flag = ByteBuffer.wrap(inBytes, startPos, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();
size = ByteBuffer.wrap(inBytes, startPos + 4, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();       

然后执行此操作以检查此结果

if(flag == Bytes.toInt("DIVA".getBytes()))
{
// do sth.
}

我希望我已经清楚地表达了自己。 :)

我的问题是上面两种方式,哪种更好?或者有更好的方法吗?

更重要的是,Chunk被用作文件的头部。

好吧,我想我明白了。

0 个答案:

没有答案
相关问题