Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trying to read binary data byte by byte from a file on disk.

Status
Not open for further replies.

nipester

Technical User
Oct 23, 2003
54
US
I am trying to read data from a small binary file, byte by byte and then print each byte to console. Heres the code:

#include "stdafx.h"
#include <fstream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
ifstream snoop;
snoop.open("c:\\data.bin", ios::in | ios::binary);
char character1;
int counter;
counter=1;
while (counter<50)
{
snoop.get(character1);
cout << "\nAscii character: " << character1;
cout << " hexadecimal rep: " << hex << int(character1);
cout << " decimal rep: " << dec << int(character1);
counter=counter+1;
}
return 0;
}


Its supposed to print the ascii character equivalent and then the actual ascii code number in hex and decimal. Problem is that the type char doesnt go upwards of 128 in value so any byte that coincidentally happens to be between 129 and 255 in value will go negative because type char is from -128 to +128. I recognised this problem but my new problem is that get() doesnt work on unsigned chars.
 
I think the simplest way to go:
Code:
char ch;
unsigned uch;
...
snoop.get(ch);
uch = (unsigned)ch&0xFF; // to print int values of char
...
It's a common issue. The char type in C/C++ may be signed or unsigned (it's implementation dependent by the language Standard). So if it's signed (as in VC++) char values over 127 are negative.
If you want to treat char sign bit as a data you must provide all coersions by hands...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top