reading HEX characters
Jun 25, 2010 at 6:30pm UTC
I am trying to read from a HEX file. I am unable to compare a certain characters from the HEX, can anyone tell me what I am doing wrong?
1 2 3 4
if (line[i] == 0x88 && line[i+1] == 0xE7){
wiFlag++;
lowLim = i;
}
When I check 0x01 or 0x04, it works, but not for the above ones
Jun 25, 2010 at 7:01pm UTC
You are comparing
signed
and
unsigned
numbers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
using namespace std;
unsigned char y=0xE5; // unsigned char can store values between 0 and 255
char x=0xE5; // signed char can store values between -128 and +128, so 0xE5 becomes -27
int main()
{
if (x==0xE5) cout <<"X is equal to 0xE5" ; // comparing -27 and 0xE5
if (y==0xE5) cout <<"Y is equal to 0xE5" ; // comparing
cout <<endl;
cout <<"x== " <<(signed )x<<endl;
cout <<"y== " <<(unsigned )y<<endl;
}
So simply declare
line
as
unsigned char
instead of
char
Jun 25, 2010 at 7:04pm UTC
Thank you for the quick reply. for me line is String and not Char. Can I do the same for it too?
Jun 25, 2010 at 7:28pm UTC
You shouldn't use binary file IO and strings together.
Here's an example how to do this properly:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <fstream>
#include <csignal>
#include <iostream>
using namespace std;
int main()
{
fstream file("hex.dat" );
// get file size
file.seekg(0,ios::end);
int file_size=file.tellg();
file.seekg(0,ios::beg);
cout <<"File size : " <<file_size<< "bytes" <<endl;
unsigned char *data=new unsigned char [file_size]; // allocate space for file
file.read( (char *)data,file_size);
for (int i=0;i<file_size;i+=2)
{
if (data[i] == 0x88 && data[i+1] == 0xE7)
{
// your code here
}
}
delete [] data;
file.close();
}
http://www.cplusplus.com/reference/iostream/fstream/
http://www.cplusplus.com/reference/iostream/istream/read/
Hope this helps.
Last edited on Jun 25, 2010 at 7:29pm UTC
Topic archived. No new replies allowed.