user3799358
user3799358

Reputation: 15

Scan values of hex string

I have a hex string like this 00133587a1bddb8dae00a3a01a010100, which is actually 7 hex strings concatenated that when expanded out look like this 00 133587a1 bddb8dae 00a3a01a 01 01 00. I'm trying to scan the first 5 of those values into this struct

typedef struct __param_value{
    uint8_t sytem_id;
    uint8_t comp_id;
    uint16_t seq;
    uint8_t frame;
    uint16_t command;
    uint8_t current;
    uint8_t autocontinue;
    float param1;
    float param2;
    float param3;
    float param4;
    float x;//param7
    float y;//param8
    float z;//param9
    uint8_t fwt;

}param_value

and the last 2 into these variables

    int txtseq;
    int cont=1;

by using sscanf, like this

sscanf(in_str,"%2x%8x%8x%8x%2x%2x%2x",&(points[wp].seq),&(points[wp].x),&(points[wp].y),&(points[wp].z),&(points[wp].fwt),&txtseq,&cont);

but I can't figure out the correct syntax. Is it possible to do it this way?

Upvotes: 1

Views: 843

Answers (1)

Weather Vane
Weather Vane

Reputation: 34585

You must pass the address of unsigned int to scan data for the %x format specifier. Then you can convert to the proper data type.

#include <stdio.h>

typedef unsigned char uint8_t;
typedef unsigned short uint16_t;

typedef struct param_value{
    uint8_t sytem_id;
    uint8_t comp_id;
    uint16_t seq;
    uint8_t frame;
    uint16_t command;
    uint8_t current;
    uint8_t autocontinue;
    float param1;
    float param2;
    float param3;
    float param4;
    float x;//param7
    float y;//param8
    float z;//param9
    uint8_t fwt;
}param_value;

int main(void) {
    char hexstr [] = "00133587a1bddb8dae00a3a01a010100";
    unsigned v1, v2, v3, v4, v5, v6, v7;
    param_value rec;
    int txtseq;
    int cont;

    if (7 != sscanf(hexstr, "%2x%8x%8x%8x%2x%2x%2x", &v1, &v2, &v3, &v4, &v5, &v6, &v7))
    {
        printf ("Bad scan\n");
        return 1;
    }

    rec.seq = (uint16_t)v1;
    rec.x   = (float)v2;
    rec.y   = (float)v3;
    rec.z   = (float)v4;
    rec.fwt = (uint8_t)v5;
    txtseq  = (int)v6;
    cont    = (int)v7;

    printf("%u %f %f %f %u %d %d\n", rec.seq, rec.x, rec.y, rec.z,
                                     rec.fwt, txtseq, cont);
    return 0;
}

Program output:

0 322275232.000000 3185282560.000000 10723354.000000 1 1 0

But: you have not mentioned whether the y value bddb8dae is intended to be negative.

Upvotes: 2

Related Questions