I can't wrap my head around how I can use char arrays (the first argument of std::ifstream.read() to compare different types of data).
For example, if I was trying to read the magic of a Windows PE file, I am doing this but I feel there are better ways around it since, to my knowledge, this requires I define every pre-assumed value in the file as a std::array:
std::array<char, 2> magic;
in.read(magic.data(), magic.size());
std::array<char, 2> shouldBe = { 0x4d, 0x5a }; // MZ for dos header
if(magic == shouldBe) {
// magic correct
}
This gives me compiler warnings like invalid conversion from int to char. I also don't quite understand how I'd read in the magic for other files where the hex values don't at all correlate to ASCII characters. For example, every Java class file starts with 0xCAFEBABE is a magic yet when I read it in as 4 chars and then cast each part to an int, I get padding which I don't want on the left.
char* magic = new char[4];
in.read(magic, 4);
// how can I compare this array to 0xCAFEBABE?
Output when I loop through each part and then cast as int and use std::hex in the output stream:
ffffffca fffffffe ffffffba ffffffbe
What's the best way to parse lots of different types of values used in binary file formats like PE files and Java classes?
charbecause it could besignedor other. Useuint8_t, which is an unsigned 8 bit quantity. You can cast it to thechartype inside theread()parameter:in.read((char *) magic, 4);std::array<char, 4> magic; inClass.read(magic.data(), 4); std::array<char, 4> classMagic = { 0xCA, 0xFE, 0xBA, 0xBE };warning: narrowing conversion of '202' from 'int' to 'char' inside { } [-Wnarrowing] std::array<char, 4> classMagic = { 0xCA, 0xFE, 0xBA, 0xBE }; ^