做一些经验来理解位域
嗨有这个代码:
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
。
为什么会这样?