This question already has answers here:
What is the strict aliasing rule?
                                
                                    (11个答案)
                                
                        
                        
                            Why bit endianness is an issue in bitfields?
                                
                                    (7个答案)
                                
                        
                                2年前关闭。
            
                    
我正在尝试使用uint8_t字段将structure缓冲区类型转换为bit,如下所示。

#include<stdio.h>
#include<inttypes.h>

struct msg{
    uint64_t field:56;
};

void main()
{
   uint8_t buf[8]={0x7,0x6,0x5,0x4,0x3,0x2,0x1};
   struct msg *m = buf;
   printf("buf=%"PRIx64"\n",m->field);
}


但是我得到的输出如下。


  实际输出:
  
  buf=1020304050607
  
  预期产量:

buf=7060504030201



类型转换时我做错什么了吗?

最佳答案

您可以使用联合体来提高可移植性,而不必进行指针修饰

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


typedef union
{
    struct
    {
        uint64_t u56:56;
    };
    uint8_t u8[sizeof(uint64_t)];
}msg;


msg *pune(msg *message, uint8_t *data, size_t datalen, int endianes)
{
    if(endianes)
    {
        for(size_t index = 0; index < datalen; index++)
        {
            message -> u8[index] = data[index];
        }
    }
    else
    {
        for(size_t index = 0; index < datalen; index++)
        {
            message -> u8[index] = data[datalen - index - 1];
        }
    }
    return message;
}


int main()
{
    msg message;
    uint8_t buf[8]={0x7,0x6,0x5,0x4,0x3,0x2,0x1};

    printf("buf=%llx\n",pune(&message, buf, 7, 1) -> u56);
    printf("buf=%llx\n",pune(&message, buf, 7, 0) -> u56);
    return 0;
}

关于c - 从unit8_t缓冲区到结构的指针类型转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52146548/

10-13 03:30