Hi I am reading in a binary file formatted in hex. It is an image file below is a short example of the first few lines of code using hd … |more command on linux. The image is a binary graphic so the only pixel colours are either black or white. It is a 1024 by 1024 image however the size comes out to be 2097152 bytes
00000000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |…………….|
000dfbf0 00 00 00 00 00 00 00 00 00 00 00 00 ff 00 ff 00 |…………….|
000dfc00 ff 00 ff 00 ff 00 00 00 00 00 00 00 00 00 00 00 |…………….|
000dfc10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |…………….|
This is the code I am using to read it in found in another thread on SO
ifstream file (argv[1], ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize;
char* fileContents;
if(file.is_open())
{
fileSize = file.tellg();
fileContents = new char[fileSize];
file.seekg(0, ios::beg);
if(!file.read(fileContents, fileSize))
{
cout << "fail to read" << endl;
}
file.close();
cout << fileSize << endl;
The code works however when I run this for loop
for (i=0; i<2097152; i++)
printf("%hd",fileContents[i]);
The only thing printed out are zeros and no 1s. Why is this are my parameters in printf not correctly specifying the pixel size. I know for a fact that there are 1’s in the image representing the white areas. Also how do i figure out how many bytes represent a pixel in this image.
Your
printf()is wrong.%hdmeansshort, whilefileContents[i]is achar; on all modern systems I’m familiar with, this is a size mismatch. Use an array ofshortinstead, since you have twice as many bytes as pixels.Also, stop using
printf()and usestd::cout, avoiding all type mismatch problems.