2

There are some codes in C++ like this:

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

Then write in to a file(fp is a pointer of file):

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

When in Java, to read the chunk, I need to do this

// 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);

Then, to check the result

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

Or do it this way in java('Bytes.toInt' is from 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();       

Then do this to check this result

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

I hope I have expressed myself clearly. :)

My question is that two ways above, which is better ? Or is there a better way ?

What's more, Chunk is used as the head of a file.

Well, I think I get it.

Destiny
  • 466
  • 5
  • 8
  • 1
    Do you know a lot of C++ people hate the term "C/C++" since C and C++ are two distinct (though related) languages? –  Feb 10 '15 at 03:21
  • @Nicky C Sorry, I don't know. =.= – Destiny Feb 10 '15 at 03:25
  • 2
    @WhozCraig Isn't that a multibyte character? http://stackoverflow.com/questions/7459939/what-do-single-quotes-do-in-c-when-used-on-multiple-characters. It is valid just implementation defined. – FDinoff Feb 10 '15 at 06:00
  • @FDinoff I really need to get out of crappy Windows world, man. Thanks for the link. Don't drop that comment. its *very* helpful. Certainly the storage is also implementation defined, so assuming little-endian on either of these isn't safe regardless. Thanks again for the link! – WhozCraig Feb 10 '15 at 06:04

0 Answers0