I have a program that takes the contents of a file and convert it into a hex. I would like to take those hex values and store them as elements of an unsigned char
array I've called hexData. How would I go about this?
I've tried converting the hex data into a string literal
(for example 0x5A
) and casting it to a char*
, but when I try running the code nothing happens (no output, no errors). It also seems like a very inefficient way of doing this. I've left the code in to see what I mean.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
typedef unsigned char BYTE;
typedef unsigned short int WORD;
int main()
{
ifstream ifd("C:\\Users\\Shayon Shakoorzadeh\\Documents\\test.txt", ios::binary | ios::ate);
int size = ifd.tellg();
ifd.seekg(0, ios::beg);
vector<char> buffer;
buffer.resize(size);
ifd.read(buffer.data(), size);
static BYTE hexData[100000] =
{
};
string tempStr;
char *tempChar;
const int N = 16;
const char hex[] = "0123456789ABCDEF";
char buf[N*4+5+2];
for (int i = 0; i < buffer.size(); ++i)
{
int n = i % N;
// little endian format
if (i > 0 && i < buffer.size()-1)
swap(buffer[i], buffer[i+1]);
// checks to see if at the end
if (n == 0)
{
memset(buf, 0x20, sizeof(buf));
buf[sizeof(buf) - 3] = '\n';
buf[sizeof(buf) - 1] = '\0';
}
unsigned char c = (unsigned char)buffer[i];
// storing the hex values
buf[n*3+0] = hex[c / 16];
buf[n*3+1] = hex[c % 16];
//encoded buffer
buf[3*N+5+n] = (c>=' ' && c<='~') ? c : '.';
//my attempt
tempStr = "0x" + string(1, hex[c / 16]) + string(1, hex[c % 16]);
tempChar = (char*)alloca(tempStr.size() + 1);
memcpy(tempChar, tempStr.c_str(), tempStr.size() + 1);
strcpy( (char*) hexData[i] , tempChar);
}
}
The static BYTE hexData[] array would need to have values that look like:
{0x5A, 0x00, 0x7F, 0x90, 0x8A,...}
and so on
Any help would be greatly appreciated!
EDIT:
Let me specify, I am having trouble STORING these values into my array called "hexData." I am already getting the hex values from my file, but only as a string. I want to convert these strings into unsigned chars so they can be put into my hexData array. Sorry my original question was worded so poorly, but I do not believe the pointed to duplicate question answers my question.