答案 0 :(得分:2)
非常相似:
const char* string_to_hex(const char *str, char *hex, size_t maxlen)
{
static const char* const lut = "0123456789ABCDEF";
if (str == NULL) return NULL;
if (hex == NULL) return NULL;
if (maxlen == 0) return NULL;
size_t len = strlen(str);
char *p = hex;
for (size_t i = 0; (i < len) && (i < (maxlen-1)); ++i)
{
const unsigned char c = str[i];
*p++ = lut[c >> 4];
*p++ = lut[c & 15];
}
*p++ = 0;
return hex;
}
int main()
{
char hex[20];
const char *result = string_to_hex("0123", hex, sizeof(hex));
return 0;
}
答案 1 :(得分:0)
只需对std :: string使用相同的函数,但使用char *,
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
using namespace std;
char *string_to_hex(char *input) {
static const char *const lut = "0123456789ABCDEF";
size_t len = strlen(input);
int k = 0;
if (len & 1)
return NULL;
char *output = new char[(len / 2) + 1];
for (size_t i = 0, j = 0; i < len; i++, j += 2) {
const unsigned char c = input[i];
output[j] = lut[c >> 4];
output[j + 1] = lut[c & 15];
}
return output;
}
std::string string_to_hex(const std::string &input) {
static const char *const lut = "0123456789ABCDEF";
size_t len = input.length();
std::string output;
output.reserve(2 * len);
for (size_t i = 0; i < len; ++i) {
const unsigned char c = input[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
}
return output;
}
int main() {
string test = "Test";
std::string res(string_to_hex(test.c_str()));
cout << res << endl;
res = string_to_hex(test);
cout << res << endl;
}
答案 2 :(得分:0)
您剪辑的两个代码看起来像相反的代码。
char* string_to_hex(const char* input) {
static const char* const lut = "0123456789ABCDEF";
size_t len = strlen(input);
char* output = new char[len*2+1];
int index = 0;
for(size_t i = 0; i < len; ++i) {
const unsigned char c = input[i];
output[index++] = lut[c >> 4];
output[index++] = lut[c & 15];
}
output[index] = '\0';
return output;
}
这是字符串 - &gt; char *版本的第一个代码。