Responsive Ad Area

Share This Post

test

Reading hex numbers as 2 digits per char from bin file -c++

I am writing a c++ program to read a bin file.The binary file has the following sample contents.

10 00 01 02 20 03 04 40 50 .....

The problem here is by using normal read from bin file the byte 10 ,40, 50 are read correctly. But in case of 00, 01, 02 03…. they are read as 0, 1, 2 ,3 respectively.

But i want them also to be read as 00 01 02 03. The reason being, i am trying to convert the values to binary. so i want to get the binary equivalent of “10 00 01 02” which is 10000000000000000000100000010. But because the the contents are being interpreted as 10012, i get 10000000000010010 as the result. Please do help me in solving this. Sorry if the content is too lengthy. Thanks in advance.

I used the following code. // cut shorted for simplicity

fstream fp;
fp.open(binFile, ios::binary | ios::in);
char * buffer = new char[4];
// read data as a block:
fp.read(buffer, 4);
// copied the contents to a string
stringstream ss;
for (std::string::iterator it = temp.begin(); it != temp.end(); ++it)
{
    ss << hex << unsigned(*it);
}
ss >> intvalue; // stores the converted hex value 
string binstring = bitset<32>(intvalue).to_string();
cout<<binstring // produces wrong value. 


Reading hex numbers as 2 digits per char from bin file -c++
Reading hex numbers as 2 digits per char from bin file -c++
test
{$excerpt:n}

Share This Post

Leave a Reply

Your email address will not be Publishedd. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Skip to toolbar