Reputation: 615
I'm sure this is a simple question, but I'm trying to output the hexadecimal value of each byte in a file (*.bmp in this case). I have successfully loaded the file in memory, and am able to print hex values of bytes. but when I print certain bytes,When I print certain bytes, for example the 3rd byte (at offset 2), it prints FFFFFFE6, but my hexdump(using HxD) of the file says it is just E6. This happens only on certain bytes, the others print just fine.
Main.cpp is:
#include "main.h"
int main ()
{
ifstream::pos_type size;
char * memblock;
ifstream file ("C:\\hex.bmp", ios::in|ios::binary|ios::ate);
size = file.tellg();
memblock = new char [size];
file.seekg(0, ios::beg);
file.read(memblock, size);
file.close();
printf("%X", memblock[2]);
delete[] memblock;
cin.get();
}
Main.h is:
#ifndef MAIN_H
#define MAIN_H
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
#endif
Upvotes: 1
Views: 139
Reputation: 477040
You need to understand how variable arguments and standard integral conversions work. When you char
is signed, you're in trouble.
Always print bytes as unsigned chars:
char data[100];
printf("%02X", (unsigned char)data[i]);
// ^^^^^^^^^^^^^^^
Upvotes: 6