如何获取结构中任何成员的位位置 [英] How to get the bit position of any member in structure

查看:15
本文介绍了如何获取结构中任何成员的位位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取结构中任何成员的位位置?

How can I get the bit position of any members in structure?

示例中>

typedef struct BitExamStruct_
{
    unsigned int v1: 3;
    unsigned int v2: 4;
    unsigned int v3: 5;
    unsigned int v4: 6;
} BitExamStruct;

有没有像GetBitPos(v2, BitExamStruct)这样的宏来获取任何成员的位位置?

Is there any macro to get the bit position of any members like GetBitPos(v2, BitExamStruct)?

我认为编译器可能会根据结构中的位长知道成员的位置.所以我想知道我是否可以通过使用简单的宏而不运行代码来获得它.

I thought that compiler might know members' location based on bits length in the structure. So I want to know whether I can get it by using just a simple macro without running code.

提前致谢.

推荐答案

据我所知,没有标准的方法可以这样做,但这并不意味着您找不到解决方案.

There is no standard way that I know of to do so, but it doesn't mean you can't find a solution.

以下不是最漂亮的代码;这是一种识别变量在内存中开始"位置的技巧.请记住,根据字节顺序,以下内容可能会产生不同的结果:

The following is not the prettiest code ever; it's a kind of hack to identify where the variable "begins" in memory. Please keep in mind that the following can give different results depending on the endianess:

#include <stdio.h>
#include <string.h>

typedef struct s_toto
{
  int a:2;
  int b:3;
  int c:3;    
} t_toto;

int
main()
{
  t_toto toto;
  unsigned char *c;
  int bytes;
  int bits;

  memset(&toto, 0, sizeof(t_toto));
  toto.c = 1;
  c = (unsigned char *)&toto;
  for (bytes = 0; bytes < (int)sizeof(t_toto); bytes++)
    {
      if (*c)
        break;
    }
  for (bits = 0; bits < 8; bits++)
    {
      if (*c & 0b10000000)
        break;
      *c = (*c << 1);
    }
  printf("position (bytes=%d, bits=%d): %d\n", bytes, bits, (bytes * 8) + bits);
  return 0;
}

我所做的是将整个结构初始化为 0,并将 1 设置为我想要定位的变量的值.结果是结构中只有一位被设置为 1.然后我读取每个字节的内存字节,直到找到一个不为零的字节.找到后,我可以查看它的位,直到找到设置的位.

What I do is that I initialize the whole structure to 0 and I set 1 as value of the variable I want to locate. The result is that only one bit is set to 1 in the structure. Then I read the memory byte per byte until I find one that's not zero. Once found, I can look at its bits until I find the one that's set.

这篇关于如何获取结构中任何成员的位位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆