Use the strtoull
function to convert a string to a number in a given base. Then just shift out the desired bytes. Such as:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
unsigned long long res = strtoull("DABC95C1", NULL, 16);
printf("%hhx, %hhx, %hhx, %hhx",
(unsigned char)res,
(unsigned char)((res >> 8) & 0xFF),
(unsigned char)((res >> 16) & 0xFF),
(unsigned char)((res >> 24) & 0xFF)
);
return 0;
}
result:
c1, 95, bc, da
Demo
Notes:
As your requirement is to get an array of bytes, you might be tempted to do something like
uint8_t *arr = (uint8_t*)&res;
But here are two caveats in this:
1) I is a strict aliasing rule violation (you can somehow to work around it by replacing uint8_t
with char
)
2) The order of the returned bytes will be implementation specific (endianness dependent) and thus not portable. Also note that the result is unsigned long long
, so you might get extra padding zeros as either the beginning of the array or in the end of it.