I am trying to achieve converting a binary content read from a file to a byte continuously .
My file samplefile.bin
contains 16bytes and this is in the form of binary . In the Hexed.it it will show like this .
What I needed in this case is I need to extract these binary values in Hex format and store it to a char *
I will post my sample code over here.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
uint8_t *ptr;
long size;
ifstream file ("samplefile.bin", ios::in|ios::binary|ios::ate);
size = file.tellg();
std::vector<uint8_t> memblock(size);
file.seekg (0, ios::beg);
file.read(reinterpret_cast<char*>(&memblock[0]), size);
file.close();
ptr = new uint8_t[size];
int z=0;
for(int i=0; i < memblock.size(); i++)
{
std::cout << memblock.at(i) << ' ';
z=memblock.at(i)&0xff;
ptr[i] = z;
}
cout<<"Output"<<endl;
for (int i=0;i<memblock.size();i++)
{
cout<<ptr[i];
}
delete []ptr;
return 0;
}
I want the ptr
to be passed to some other function. But the output of this print cout<<ptr[i]<<endl;
is like below which means the conversion is not happening.
╠ ↕ ‼ ¶ ╙ O N ╥ í * : J Z [ \ J
I want something like below
ptr[0] = 0xCC
ptr[1] = 0x12
...
ptr[15] = 0x4A
When I give like this cout<<(int)ptr[i]<<endl;
, I am getting the decimal value of 0xCC
as 204
and the same thing for other prints.
I already referred to C++ read binary file and convert to hex and Convert binary file to hex notation. I didn't find the exact solution because in these two links they are converting it to string. My intention is not this one.
I referred to this How properly to read data from binary file to char array which looks similar to mine. But it didn't solve my issue.
I want this 0xCC
as a single byte and this should be stored to ptr[0]
and similarly for the other values
How to workaround this issue ? Am I missing something here ? I am a newbie in C++ and please help me to resolve this issue
Appreciating the efforts.