I have a binary file. i am reading 16 bytes at a time it using fstream.
I want to convert it to an integer. I tried atoi. but it didnt work. In python we can do that by converting to byte stream using stringobtained.encode('utf-8') and then converting it to int using int(bytestring.hex(),16). Should we follow such an elloborate steps as done in python or is there a way to convert it directly?
ifstream file(binfile, ios::in | ios::binary | ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char[size];
file.seekg(0, ios::beg);
while (!file.eof())
{
file.read(memblock, 16);
int a = atoi(memblock); // doesnt work 0 always
cout << a << "\n";
memset(memblock, 0, sizeof(memblock));
}
file.close();
Edit:
This is the sample contents of the file.
53 51 4C 69 74 65 20 66 6F 72 6D 61 74 20 33 00
04 00 01 01 00 40 20 20 00 00 05 A3 00 00 00 47
00 00 00 2E 00 00 00 3B 00 00 00 04 00 00 00 01
I need to read it as 16 byte i.e. 32 hex digits at a time.(i.e. one row in the sample file content) and convert it to integer. so when reading 53 51 4C 69 74 65 20 66 6F 72 6D 61 74 20 33 00, i should get, 110748049513798795666017677735771517696
But i couldnt do it. I always get 0 even after trying strtoull. Am i reading the file wrong, or what am i missing.
atoi()converts a null terminated text string to an integer. Unless your 16 bytes all have the last byte set to'\0', and the previous fifteen bytes consist of leading whitespace, an optional minus sign, and at least one more character between '0' and '9', thenatoi()will not work, because that's what it does, and the only thing that it does (technically, the '\0' doesn't have to be the last byte, but that's not a relevant detail).intis typically 4 bytes, which can't store a 16 byte value.size = file.tellg();I believe this should return 0 since the file was just opened. Also,sizeof(memblock)will return the size of the pointer, not the length of the buffer.ios::atedoes. That part of the code is fine.