Is this short way for printing the string in hex is correct? If not, how it should be fixed?
uint8_t *m = string;
int c = sizeof(string);
while(c--){
printf("%02x ", *(m++));
}
Is this short way for printing the string in hex is correct? If not, how it should be fixed?
uint8_t *m = string;
int c = sizeof(string);
while(c--){
printf("%02x ", *(m++));
}
No "oneliner", no. Besides, your code looks broken.
You can't use sizeof like that, you probably mean strlen().
And you need to cast the character to an unsigned type to be safe.
So, something like this, perhaps:
void print_hex(const char *s)
{
while(*s)
printf("%02x", (unsigned int) *s++);
printf("\n");
}
Note that I don't call strlen(), since there's no point in iterating over the string twice when once will do. :)
I think technically "string" is misleading here; you seem to be printing an array (not necessarily null-terminated) of uint8_t values.
You will need a loop in any case. If you can use C99, you could write
for (size_t i = 0; i < sizeof(string); ++i) printf("%02x", string[i]);
If the array is null-terminated, and you don't need the original value of string (this is often a case when passing the pointer by value), you could have
static void printArray(const uint8_t *string)
{
while (*string) printf("%02x", *string++);
}