Doritos
Doritos

Reputation: 423

Converting unsigned char pointer of data to struct containing ints

I am trying to cast this pointer of data to my struct and the actual value populate in the struct.

unsigned char *data = "00000001000000020000000300000004AE93KD93KD91Q830DMNE03KEkdaredgreenblueorangeyellow";

typedef struct mystruc {
    int a;
    int b;
    int c;
    int d;
} mystruc;

mystruct ms = (mystruct *)data;

printf("%i", ms->a);

Output:

808464432 

I am trying to find out how to fill in a, b, c, d with the actual values 1, 2, 3, 4

I would like the output to be:

1

I will also need to later access the rest of the data.

Upvotes: 2

Views: 745

Answers (2)

Barmar
Barmar

Reputation: 781503

Use sscanf() to parse the numbers in the string.

mystruct ms;
sscanf(data, "%8d%8d%8d%8d", &ms.a, &ms.b, &ms.c, &ms.d);

%8d means to parse an 8-character decimal field as an int. If it's actually hexadecimal, change it to %8x.

Your code is interpreting the character codes in the string as the binary representation of the structure members, it doesn't parse it.

Upvotes: 8

ForceBru
ForceBru

Reputation: 44868

Your unsigned char is one byte wide, so "00000001" will be 3030303031 in hex, because the ASCII code for '0' is 0x30 in hex, and the ASCII for '1' is 0x31.

Your int is 4 bytes wide, so it'll capture the first 4 bytes of data, which will be 30303030 in hex, or 808464432 in decimal.

This, however, will work on a little-endian machine:

#include <stdio.h>

typedef struct mystruct {
    int a;
    int b;
    int c;
    int d;
} mystruct;

unsigned char *data = "\1\0\0\0";  // use octal numbers, not ASCII, also note the reversed order

int main(void) {
 mystruct *ms = (mystruct *)data;

 printf("%i", ms->a); // outputs: 1
}

Upvotes: -1

Related Questions