How can i convert a char array of number to byte array? Example:
char *digit="3224833640520308023"//long long array
convert to:
uint8_t buff[256]= {0x2c, 0xc0, 0xe9, 0x1c, 0x32, 0xf1, 0x55, 0x37, 0};
(2c c0 e9 1c 32 f1 55 37)
How can i convert a char array of number to byte array? Example:
char *digit="3224833640520308023"//long long array
convert to:
uint8_t buff[256]= {0x2c, 0xc0, 0xe9, 0x1c, 0x32, 0xf1, 0x55, 0x37, 0};
(2c c0 e9 1c 32 f1 55 37)
I printed in reverse order in the end. You may want to endian swap if you need the array in that endian order.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *digit="3224833640520308023";
int main() {
int i;
unsigned char byteArray[16];
unsigned long long x = strtoull(digit,0,10);
printf("%llx\n",x);
printf("%llu\n",x);
for (i=0;i<8;i++) {
byteArray[i] = (x>>(i*8)) & 0xFF;
}
printf ("Array is:\n");
for (i=7;i>=0;i--) {
printf("%2.2x ",byteArray[i]);
}
return 0;
}
strtoull converts the string to a 64 bits internal representation.
htobe64 will switch the endianness to big endian (the one you used in your example) if needed on your platform.
You can then copy 8 bytes from this big endian 64bit variable to your byte array.
#include <stdint.h>
#include <endian.h>
#include <stdio.h>
#include <string.h>
char *digit="3224833640520308023";
main ()
{
uint64_t ull;
uint64_t beull;
uint8_t buff[8];
int i;
ull=strtoull(digit,0,10);
beull=htobe64(ull);
memcpy(buff,&beull,8);
for(i=0;i<8;i++)
{
printf("%02x\n",buff[i]);
}
}