Reputation: 4853
Recently I have been working on my own Java 8 Bytecode decompiler. I'm having a problem with checking the magic of a class file in a nice way.
Let's say I have a unsigned char array and the elements 0 to 3 are the magic, for total of 4-bytes of magic.
The following doesn't look like a very appealing way to write the magic check:
if ((data[0] != 0xCA) && (data[1] != 0xFE) && (data[2] != 0xBA) && (data[3] != 0xBE))
{
...
}
Would it be possible to write in a shorter manner? Like:
if (data[0 to 4] != 0xCAFEBABE)
{
...
}
Code is available here, the relevant part being located here.
Upvotes: 0
Views: 183
Reputation: 2822
Yes, it is possible:
if (reinterpret_cast<uint32_t*>(data)[0] != 0xCAFEBABE)
{
...
}
Depending on the endianes of your machine, you'll have to compare to 0xCAFEBABE
or 0xBEBAFECA
.
Upvotes: 2
Reputation: 6875
There are several ways to do it.
1.One option is to use uint32_t *
.
uint32_t *val_4BytePtr = reinterpret_cast<uint32_t*>(data);
if (*val_4BytePtr == 0x...)
The downside of this option is that it may be not portable since the result which will be in *val_4BytePtr
will depend on the "endian" policy (big endian/little endian).
2.Secont option is to combine such uint32_t
uint32_t val_4Byte = (static_cast<uint32_t>(data[3]) << 24) |
(static_cast<uint32_t>(data[2]) << 16) |
(static_cast<uint32_t>(data[1]) << 8) | data[0];
if (val_4Byte == 0x...)
In this case the data stored in val_4Byte
will always have the same format.
Upvotes: 1
Reputation: 1932
Try memcmp
Compares the first num bytes of the block of memory pointed by ptr1 to the first num bytes pointed by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not.
http://www.cplusplus.com/reference/cstring/memcmp/
Upvotes: 0