My problem is converting array of chars to array of hexadecimal numbers, i need to take 2chars from char array and conver them into one hex number.
This is my input:
Some easy implementations
unsigned char text[1024] = "06fb7405eba8d9e94fb1f28f0dd21fdec55fd54750ee84d95ecccf2b1b48";
unsigned char result[512];
int size = 60;
assert(size % 2 == 0);
for (int i = 0; i + 1 < size; i += 2)
{
std::string s(text + i, text + i + 2);
auto x = std::stoi(s, 0, 16);
result[i / 2] = x;
}
// or
for (int i = 0; i + 1 < size; i += 2)
{
unsigned char c1 = *(text + i);
unsigned char c2 = *(text + i + 1);
char buffer[] = { c1, c2, 0 };
auto x = std::strtol(buffer, 0, 16);
result[i / 2] = x;
}
In this case the result is the half size of the input. Two chars are leading to one value in the result. If this is a time critical routine you may write your own conversion from two chars in a number.
en,my english is bad,so i write the code hope to explain what i think. personally speacking i think we can write a function for this question.
#include <iostream>
#include <map>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;
map<string, int> convertTable;
void initHexTable();
void convertToHex(unsigned char * text, unsigned char * hexval, int &i);
void print(unsigned char *p, int len);
char hexIndex[] = {'0','1','2','3','4','5','6','7','8','9','a', 'b', 'c', 'd', 'e', 'f'};
int main() {
unsigned char text[1024]= "06fb7405eba8d9e94fb1f28f0dd21fdec55fd54750ee84d95ecccf2b1b48";
unsigned char hexval[1024];
int len = 0;
initHexTable();
convertToHex(text, hexval, len);
print(hexval, len);
return 0;
}
void initHexTable() {
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
string key;
key += hexIndex[i]; key += hexIndex[j];
//cout << key << " ";
convertTable[key] = i * 16 + j;
}
}
}
void convertToHex(unsigned char * text, unsigned char * hexval, int &i) {
string s((char *)text);
string key;
int str_size = strlen((char*)text);
//cout << "str_size = " << str_size;
int start = 0, len = 2;
for (;;) {
if (start >= str_size) break;
key = s.substr(start, len);
//cout << " "<<convertTable[key]<< " ";
hexval[i++] = convertTable[key];
start += 2;
}
}
void print(unsigned char *p, int len) {
for (int i = 0; i < len; i++) {
printf("0X%03d ", p[i]);
if (!((i + 1) % 4)) puts("");
}
}