[英]converting ASCII char array to hex char array
I am trying to convert an ASCII char array to hex char array to do something like this:我正在尝试将 ASCII 字符数组转换为十六进制字符数组以执行以下操作:
Input: char string[5]="abcd1234567"
输入: char string[5]="abcd1234567"
Output: char buf[4096] = {0x63, 0x61, 0x62, 0x63, 0x64, 0x31, 0x32, 0x33 0x34, 0x35, 0x36, 0x37};
Output: char buf[4096] = {0x63, 0x61, 0x62, 0x63, 0x64, 0x31, 0x32, 0x33 0x34, 0x35, 0x36, 0x37};
but my code didn't work and i couldn't figure it out.但我的代码不起作用,我无法弄清楚。
code:代码:
char string[20]="abcd";
char buff[4000];
sprintf(buff[0],"%02x",string[0]);
printf("string[0]: %c",string[0]);
it gives this error:它给出了这个错误:
warning: passing argument 1 of 'sprintf' makes pointer from integer without a cast [-Wint-conversion]
16 | sprintf(buff[0],"%02x",string[0]);
There's no difference between 'c'
and 0x63
on an ASCII-based machine, so all you need is the following:在基于 ASCII 的机器上, 'c'
和0x63
没有区别,所以您只需要以下内容:
char buf[4096];
strncpy(buf, string, sizeof(buf));
That technically does从技术上讲
char buf[4096] =
{0x63, 0x61, 0x62, 0x63, 0x64, 0x31, 0x32, 0x33 0x34, 0x35, 0x36, 0x37, 0};
^^^
|||
But that's equivalent giving the extra room in buf
.但这相当于在buf
中提供了额外的空间。 Use memcpy
if you want to avoid that extra NUL.如果您想避免额外的 NUL,请使用memcpy
。
Implementation of converting each pair of hex string characters to their byte values.将每对十六进制字符串字符转换为其字节值的实现。 Explanations are in the comments:解释在评论中:
void convertStringToByteArray(const char* string, unsigned char* output)
{
// i+=2 will ignore a trailing single character if you don't have an even number of them,
// such as the case in string above
for (size_t i=0; i<strlen(string); i+=2)
{
// create a substring
char temp[3];
temp[0] = string[i];
temp[1] = string[i+1];
temp[2] = '\0';
// there's quite a bit of error checking here that's possible, but since we're dealing
// with bytes, we only really need to check if temp contains valid hex data. There
// should be no danger of under or overflow
char* endptr;
// convert temp to a long. If there's a problem, *endptr will point to the invalid
// char. Use 16 to specify this is a hex string
long convert = strtol(temp, &endptr, 16);
if (*endptr == '\0')
{
// no problems
output[i/2] = convert;
}
else
{
// invalid hex, just fill in with 0? You can do what you want here
output[i/2] = 0;
}
}
}
int main(void)
{
// no need to specify a size for string here, let the compiler do it
char string[]="abcd1234567";
// every 2 chars in string are one byte.
unsigned char output[strlen(string) / 2];
convertStringToByteArray(string, output);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.