How to get the bit position of any member in structure

吃可爱长大的小学妹 提交于 2021-02-07 09:51:50

问题


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

In example>

typedef struct BitExamStruct_
{
    unsigned int v1: 3;
    unsigned int v2: 4;
    unsigned int v3: 5;
    unsigned int v4: 6;
} 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.

Thank you in advance.


回答1:


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;
}

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.




回答2:


There is no portable (aka standard C) way. But thinking outside the box, if you need full control or need this information badly, bitfields are the wrong approach. The proper solution is shifting and masking. Of course this is feasible only when you are in control of the source code.



来源:https://stackoverflow.com/questions/43622253/how-to-get-the-bit-position-of-any-member-in-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!