I am using this approach to convert hex string to byte array.The code is works correct. While compiling this code I am getting below compilation warning. Is there any way I can resolve it?
/* test.c */
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: ./test <input hex string>\n");
return 0;
}
char *hexstring = argv[1];
printf("hextring:%s\n", hexstring);
uint8_t str_len = strlen(hexstring);
printf("length:%d\n", str_len);
uint8_t array_size = str_len / 2;
printf("array_size:%d\n", array_size);
uint8_t *input = (uint8_t *)calloc(array_size, sizeof(uint8_t));
for (int i = 0; i < array_size; i++)
{
sscanf(hexstring, "%02x", &input[i]);
hexstring = hexstring + 2;
}
for (int i = 0; i < array_size; i++)
{
printf("input[%d]:[%.2x]\n", i, input[i]);
}
return 0;
}
Compilation warning:
gcc test.c -o test
test.c:24:34: warning: format specifies type 'unsigned int *' but the argument has type 'uint8_t *' (aka 'unsigned char *') [-Wformat]
sscanf(hexstring, "%02x", &input[i]);
~~~~ ^~~~~~~~~
The size of uint8_t
is usually small than one of unsigned int
, so your code seems happened to work.
You should use correct format specifer.
Add
#include <inttypes.h>
at the beginning of your code and change the format "%02x"
to "%02" SCNx8
.
The SCNx8
macro will be expanded to correct format specifier and connected to the "%02"
part.
If unfortunately this is not supported in your environment, another way is to use a buffer with correct type to read the value.
for (int i = 0; i < array_size; i++)
{
unsigned int buffer = 0;
sscanf(hexstring, "%02x", &buffer);
input[i] = (uint8_t)buffer;
hexstring = hexstring + 2;
}