Is that what you wanted? (to test give binary 01 combination as an first argument)
#include <stdio.h>
#include <stdint.h>
uint8_t charToBin(char c)
{
switch(c)
{
case '0': return 0;
case '1': return 1;
}
return 0;
}
uint8_t CstringToU8(const char * ptr)
{
uint8_t value = 0;
for(int i = 0; (ptr[i] != '\0') && (i<8); ++i)
{
value = (value<<1) | charToBin(ptr[i]);
}
return value;
}
int main(int argc,const char *argv[])
{
printf("%d\n",CstringToU8(argv[1]));
return 0;
}
You can use CstringToU8() to convert 8 characters to one u8 number. Read whole data to char array (e.g. char * text) and then convert 8 characters to u8 number, store it and move you pointer 8 bytes further until array won’t end.
Because after edit question was changed so here is my new solution. Code reading hex numbers from file and storing it into array.
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
int main()
{
FILE * fp;
uint8_t number = 0;
size_t fileSize = 0;
uint8_t * array = NULL;
size_t readedBytes = 0;
size_t iterator = 0;
fp = fopen ("hexNumbers.txt", "r");
// check file size
fseek(fp, 0L, SEEK_END);
fileSize = ftell(fp);
fseek(fp, 0L, SEEK_SET);
/// allocate max possible array size = fileSize/2
array = malloc(fileSize/2 * sizeof(uint8_t));
/// read data into array
while(!feof(fp))
{
if (fscanf(fp,"%2hhx",&number) == 1)
{
array[readedBytes++] = number;
}
}
fclose(fp);
/// print array output
for (iterator=0; iterator<readedBytes; ++iterator)
{
printf("%02x ", array[iterator]);
}
free(array);
return 0;
}
2
solved read file string and store in uint8_t array in c [closed]