gpt4 book ai didi

c - 8 位输入给出奇怪的行为,因为 16/32 位给出小端/大端

转载 作者:太空宇宙 更新时间:2023-11-04 01:10:07 26 4
gpt4 key购买 nike

我有一个这样的 C 结构......

struct icmp_prefixopt {
u_int8_t icmpopt_type;
u_int8_t icmpopt_len;
u_int8_t prefixlen;
u_int8_t lflag:1;
u_int8_t aflag:1;
u_int8_t reserved:6;

};

并且我在同一个模块中为这样的成员提供了值-

   popt= (struct icmp_prefixopt *)
malloc(sizeof(struct icmp_prefixopt));

popt->icmpopt_type = 3;
popt->icmpopt_len = 4;
popt->prefixlen = (u_int8_t)strtoul(arg, (char **)NULL, 0);

arg = index(arg, '+');
if (arg) {
++arg;
popt->lflag = ((u_int8_t)strtoul(arg, (char **)NULL, 0))&1;
}


arg = index(arg, '+');
if (arg) {
++arg;
popt->aflag = ((u_int8_t)strtoul(arg, (char **)NULL, 0))&1;
}


arg = index(arg, '+');
if (arg) {
++arg;
popt->reserved = 32; //((u_int8_t)strtoul(arg, (char **)NULL, 0))<<2;
}

其中 arg 是传递给此模块的命令行参数。

现在以十六进制格式查看执行后结构的内容->

  03 04 20 81

icmpopt_type: seems fine
icmpopt_len: seems fine
prefixlen: seems fine

但对于构成字节的其他 3 个字段,位看起来像是颠倒了

  lflag:1; aflag:1; reserved:6

所以它应该是 - 10100000=A0 但实际上它们是 =>81=10000001

这给我带来了很多问题......

  1. little endian/big endian有什么关系吗?

  2. 如果是,htonl 和 htons 等 8 位函数的对应项是什么。

  3. 如果不是,可能的问题是什么,或者我完全误解了什么?

  4. 什么是最好的方法?修改结构中这些字段的顺序
    本身还是应用一些位运算符并在此处本身移位位?

命令行提供的输入-

    32+1+0+32 

这个最后的 32 在这里没有用处,因为我已经在模块本身中固定了 32 用于测试。虽然我的实际目的也需要考虑这个领域。

请尽快帮助我找到任何替代方法。

提前致谢。

编辑:

enter image description here

这是我需要创建的实际结构,在创建的同时,需要为用户提供通过 GUI 为所有字段指定值的规定。 (现在只能通过 linux 命令行)。

我想我现在已经把问题说得更清楚了,但如果需要任何进一步的信息,我会很乐意补充。

最佳答案

编译器如何选择打包位域完全取决于实现。它不一定与字节序有任何关系。

htnol(和类似的)不适用于位域。如果您需要保证订单,那么您将需要自己手动打包一个 uint8_t。例如:

struct icmp_prefixopt {
u_int8_t icmpopt_type;
u_int8_t icmpopt_len;
u_int8_t prefixlen;
u_int8_t stuff;
}

...

popt->stuff = (lflag << 7) | (aflag << 6);

当然,在实践中,您应该使用合理的 #define 而不是魔数(Magic Number)(对于 6 和 7)。您可能决定将其包装在一堆 setter 和 getter 函数中。

关于c - 8 位输入给出奇怪的行为,因为 16/32 位给出小端/大端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14348218/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com