使用定义(C)写入结构偏移量

使用定义(C)写入结构偏移量,c,struct,syntax,C,Struct,Syntax,我有一个结构,我可以通过使用两个定义IP\u V(IP)和IP\u HL(IP)来读取,但我还需要对它们进行写入。给定一个structstruct pkt\u ip,在ip\u vhl中写入低位和高位的语法是什么 struct pkt_ip { uint8_t ip_vhl; /* header length, version */ #define IP_V(ip) (((ip)->ip_vhl & 0xf0) >

我有一个结构,我可以通过使用两个定义
IP\u V(IP)
IP\u HL(IP)
来读取,但我还需要对它们进行写入。给定一个struct
struct pkt\u ip,在
ip\u vhl
中写入低位和高位的语法是什么

struct pkt_ip
{
    uint8_t         ip_vhl;         /* header length, version */
    #define IP_V(ip)        (((ip)->ip_vhl & 0xf0) >> 4)
    #define IP_HL(ip)       ((ip)->ip_vhl & 0x0f)
    uint8_t         ip_tos;         /* type of service */
    #define IP_DSCP(ip)        (((ip)->ip_tos & 0xfc) >> 4)
    #define IP_ECN(ip)       ((ip)->ip_tos & 0x3f)
    uint16_t        ip_len;         /* total length */
    uint16_t        ip_id;          /* identification */
    uint16_t        ip_off;         /* fragment offset field */
    #define IP_DF 0x4000                    /* dont fragment flag */
    #define IP_MF 0x2000                    /* more fragments flag */
    #define IP_OFFMASK 0x1fff               /* mask for fragmenting bits */
    uint8_t         ip_ttl;         /* time to live */
    uint8_t         ip_p;           /* protocol */
    uint16_t        ip_sum;         /* checksum */
    struct  in_addr ip_src,ip_dst;  /* source and dest address */
} __attribute__ ((__packed__));

您需要自己在
ip_vhl
字段上进行位操作

要设置版本,请执行以下操作:

header.ip_vhl = (header.ip_vhl & 0x0f) | ((new_version & 0xf) << 4);

我假设您希望使用范围为
0x0..0x0f
myVal
值进入
ip_vhl
的下半字节或上半字节。然后您可以使用以下语句:

ip_vhl = (ip_vhl & 0x0f) | ((myVal & 0x0f) << 4)

ip_vhl = (ip_vhl & 0xf0) | (myVal & 0x0f)
ip_vhl=(ip_vhl&0x0f)|((myVal&0x0f)
ip_vhl = (ip_vhl & 0x0f) | ((myVal & 0x0f) << 4)

ip_vhl = (ip_vhl & 0xf0) | (myVal & 0x0f)