简体   繁体   English

将数据的无符号字符指针转换为包含整数的结构

[英]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.我正在尝试将此数据指针转换为我的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我想知道如何用实际值 1、2、3、4 填充abcd

I would like the output to be:我希望输出是:

1

I will also need to later access the rest of the data.我还需要稍后访问其余数据。

Use sscanf() to parse the numbers in the string.使用sscanf()解析字符串中的数字。

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 . %8d表示将 8 个字符的十进制字段解析为int If it's actually hexadecimal, change it to %8x .如果它实际上是十六进制,请将其更改为%8x

Your code is interpreting the character codes in the string as the binary representation of the structure members, it doesn't parse it.您的代码将字符串中的字符代码解释为结构成员的二进制表示,它不会解析它。

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 .您的unsigned char是一个字节宽,因此"00000001"将是十六进制的3030303031 ,因为'0'的 ASCII 代码是十六进制的0x30 ,而'1'的 ASCII 是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.您的int宽度为 4 个字节,因此它将捕获前 4 个字节的data ,即十六进制的30303030或十进制的808464432

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM