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 the individual bytes 00 01 02 03 etc also to be read as 00 01 02 03 etc **. 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 of buffer[] to a string str
stringstream ss;
for (std::string::iterator it = str.begin(); it != str.end(); ++it)
{
ss << std::hex << unsigned(*it);
}
ss >> intvalue; // stores the converted hex value
string binstring = bitset<32>(intvalue).to_string();
cout<<binstring // produces wrong value.
Converting from single bytes to biger types of integers is typically done using bitshifts.
unsigned char * buffer = new unsigned char[4];
fp.read(buffer, 4);
uint32_t result = buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
If you want to have a string object (not a number) with the hexadecimal representation of the number with leading zeros filled up to 8 characters of hexadecimal representation, you can indeed use <<
overloaded operator with some iomanip
to print it. You have to use hex and print it with leading zeros. You have to also cast to an integer, because characters are printed like characters, not like numbers.
std::stringstream ss;
for (size_t i = 0; i < 4; ++i) {
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(buffer[i]);
}
std::string str(ss.str);
or
std::stringstream ss;
ss << std::hex << std::setw(8) << std::setfill('0') << result;
std::string str(ss.str);
If you want to have a string object with the representation of the number in base 2 including with leading zeros you can indeed use bitset
to_string()
:
for (size_t i = 0; i < 4; ++i) {
std::cout << bitset<8>(buffer[i]).to_string();
}
or again use the result
from above:
std::cout << bitset<32>(result).to_string();