2

做一些经验来理解位域

嗨有这个代码:

01  #include <stdio.h>
02  #include <stdlib.h>
03
04  void AddToBitfield(int *bitfield, int bitCount, int value);
05  int ReadFromBitfield(int *bitfield, int bitCount);
06
07  int main(){
08      /*Device list (0 Modem,1 Keyboard,2 Mouse,3 Speakers,4 Joystick,5 Flash Drive,6 Scanner,7 Printer,8 Microphone,9 Webcam,10 Monitor)*/
09      int device=0,memLoc=0,data=0;
10      int number = 0;
11
12      memLoc = 01; /*put 01 or 10*/
13      device = 15; /*Device id*/
14      data = 12343; /*Data to store - Only less or equal then 65535*/
15
16      AddToBitfield(&number,4,device);
17      AddToBitfield(&number,16,data);
18      AddToBitfield(&number,2,memLoc);
19
20      printf("--%d---\n",number);
21
22      printf("Memory location: %d\n",ReadFromBitfield(&number,2));
23      printf("Data stored: %d\n",ReadFromBitfield(&number,16));
24      printf("Device: %d\n",ReadFromBitfield(&number,4));
25
26      return 0;
27  }
28
29  void AddToBitfield(int *bitfield, int bitCount, int value){
30      *bitfield <<= bitCount;
31      *bitfield |= value;
32  }
33
34  int ReadFromBitfield(int *bitfield, int bitCount){
35      int value = *bitfield & ((1 << bitCount) - 1);
36      *bitfield >>= bitCount;
37
38      return value;
39  }

使用data = 12343;and withmemLoc = 01;memLoc = 10;printf 将按预期显示所有内容。

使用data = 12346;and withmemLoc = 01;memLoc = 10;相同的东西。printf 将按预期显示所有内容。

但是,如果我使用data = 12344;或者data = 12345;如果我使用memLoc = 01;print 将显示两种情况下的预期,但如果我memLoc = 10;在第一种情况下使用它会打印Data stored: 12346在第二种情况下Data stored: 12347

为什么会这样?

4

1 回答 1

2

您可以使用此 Cstruct来读取/写入位域:

struct MyType
{
    uint16_t memLoc:4;
    uint16_t device:4;
    uint16_t _reserved:8;
    uint16_t data;
};

您的代码将如下所示:

int main()
{
    // ...

    struct MyType number;
    uint32_t numberInt;

    number.memLoc = 1;
    number.device = 15;
    number.data = 12343;

    memcpy(&numberInt, &number, sizeof(struct MyType));
    printf("--%d---\n", numberInt);

    printf("Memory location: %d\n", number.memLoc);
    printf("Data stored: %d\n", number.data);
    printf("Device: %d\n", number.device);

    // ...
}

告诉我每个字段有多少位,我会为您修复该结构。

这是一篇关于位域的文章:http ://en.wikipedia.org/wiki/Bit_field

于 2012-04-22T17:46:06.633 回答