I am trying to convert an ASCII char array to hex char array to do something like this:
Input: char string[5]="abcd1234567"
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:
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
. Use memcpy
if you want to avoid that extra NUL.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.