Reputation: 2235
If I have an array such as this
unsigned char data[2850] = "";
that after running through a part of my program will eventually be full of byte elements such that if I loop through it and log it out I will see the following
for (size_t i= 0; i < sizeof(data); i++) {
printf("%02X ", data[i]);
}
//log window shows 01 24 81 00 0E 1C 44 etc...
Is there a way to take all the elements of the data array and put them into a const char? Or just one large string? Hopefully I'm being clear enough. My goal is to eventually turn all the elements of this data array into a base64 encoded string that I can use else where in the program.
Upvotes: 3
Views: 24975
Reputation: 76
this it work easy variable test is data type char or unsigned char
std::string User_re((char*)test);
Upvotes: -1
Reputation: 49523
A string (char array) in C is a sequencial sequence of char
s terminated by a sentianal character (the null terminator: '\0'
)
This means that if you have a byte of the value 0x00 anywhere in your array, it has thusly terminated the "string" potentially before the end of the sequence. In your example if you converted your data
array into a string the end of it would be the first element:
data[]{00, EB, 23, EC, FF, etc... };
Now if you want to make a string out of the values of the data in here, you can do that with sprintf()
, for example:
unsigned char val = 00;
data[0] = val;
char dump[5] = {0};
sprintf(dump, "%02x", data[0]);
Now you have a string with the value "00" in it, You can make it fancer with something like:
sprintf(dump, "0x%02x", data[0]);
So that it has "0x00" to show it off as hex data.
You could loop something like this to give the full string... but keep in mind that the printable string needs to be at least 2x+1 the size of the data string (2x for ASCII and +1 for null), and you have to fill the new string in steps. Example:
unsigned char data[5] = {0x00, 0x12, 0xB3, 0xFF, 0xF0};
char printstr[11] = {00};
for(int x = 0; x < 5; x++)
sprintf(printstr+(x*2), "%02x", data[x]);
printstr[10] = '\0';
Now printstr
has "0012b3fff0"
Upvotes: 3
Reputation: 609
you can use sprintf (note if you sprintf past the end of the 'str' array, you will have a buffer overflow):
//malloc 2 chars for each byte of data (for 2 hex digits)
char *str = malloc(sizeof(char) * 3 * (sizeof(data) + 1));
//this var will point to the current location in the output string
char *strp = str;
if (NULL == str)
{
return false; //memory error
}
for (size_t i= 0; i < sizeof(data); i++) {
snprintf(strp, 2, "%02X ", data[i]);
strp++;
}
// now the memory in *str holds your hex string!
Upvotes: 1