Home > Net >  Fscanf: Reading Digits seperatly in Groups of 4
Fscanf: Reading Digits seperatly in Groups of 4

Time:01-17

I have a file with Hex Data encoded in Blocks of 4 Digits.

400F
4101
6010
1000

I want to read each Digit seperatly in Blocks of 4. Like: Read 400F and save them in Seperate unsigned shorts. I could only do it with having the Digits seperated by Spaces:

uint16_t test[4];    
fscanf(file, "%hx%hx%hx%hx", &test[0], &test[1], &test[2], &test[3])

It should look like this:

test[0] -> 4
test[1] -> 0
test[2] -> 0
test[3] -> 15

(And all this ofcourse in a Loop, to get more than one line)

Can anyone help me with this? Thanks :)

CodePudding user response:

Read it into a 32-bit number using %x, then use shifting and masking to extract each digit.

uint32_t input;
uint16_t test[4];
fscanf(file, "%x", input);
test[0] = (input >> 24) & 0xf;
test[1] = (input >> 16) & 0xf;
test[2] = (input >> 8) & 0xf;
test[3] = input & 0xf;

CodePudding user response:

A width of 4, %4hx, can be used to limit the number of characters processed by fscanf, sscanf or scanf

#include <stdio.h>
#include <stdint.h>

int main ( void) {
    char input[] = "400F410160101000";
    uint16_t test[4];

    if ( 4 == sscanf ( input, "%4hx%4hx%4hx%4hx"
    , &test[0]
    , &test[1]
    , &test[2]
    , &test[3])) {
        printf ( "%hx\n", test[0]);
        printf ( "%hx\n", test[1]);
        printf ( "%hx\n", test[2]);
        printf ( "%hx\n", test[3]);
    }

    return 0;
}
  • Related