In C, I first opened a binary file like this---
FILE *BINfile = fopen("./tmp.bin", "rb+");
Then I transferred the data into an unsigned char array (typedef as byte) like this---
(Side note; I'm an amateur so I'm more comfortable with arrays)
typedef unsigned char byte;
size_t GetFileSize (FILE *file) {
fseek(file, 0, SEEK_END);
size_t Size = ftell(file);
rewind(file);
return Size;
}
byte BinFileArray[GetFileSize(BINfile)];
size_t BinReadAmount = fread(BinFileArray, 1, GetFileSize(BINfile), BINfile);
Then I wrote a function to find an int value in that bin array by first converting the int to an byte array---
size_t BinaryOffsetFinder (byte Array[], size_t ReadAmount, size_t Target) {
size_t index=0;
byte charTarget[sizeof(Target)];
byte buffer[sizeof(charTarget)];
memcpy(charTarget, &Target, sizeof(Target));
for (int i=0; i<ReadAmount; i++) {
for (int j=0; j<sizeof(buffer); j++) {
buffer[j]=Array[i+j];
}
if (buffer==charTarget) {
index=i;
break;
}
}
return index;
}
Then I ran it like this---
printf("\n%d", BinaryOffsetFinder(BinFileArray, BinReadAmount, 5019));
//I know the file has 5019 in it cause I'm modding a binary game file. Verified using ImHex
And I'm pretty confident that a lot of stuff is really wrong. Not because I'm getting 0 every time, but I seriously lack concepts here. Someone please point out the conceptual errors.
The condition if (buffer==charTarget) will always be false, because both arrays will decay to pointers to the first elements of both arrays, and these pointer values will always be different, because the addresses of the arrays are different.
If you want to instead compare the content of the arrays, you can use the function memcmp.