Doing some experiences to understand bit fields
Hi have this code:
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 } Using data = 12343; and with memLoc = 01; or memLoc = 10; the printf will show all as expected.
Using data = 12346; and with memLoc = 01; or memLoc = 10; its the same thing. The printf will show all as expected.
But if I use data = 12344; or data = 12345; if I use memLoc = 01; the print will show what is expected in both cases, but if i use memLoc = 10; on the first case it will print Data stored: 12346 and on the second case Data stored: 12347.
Why is this happening?
unsigned intfor bit fields, since left bitshifts are undefined when the left operand is negative (relevant question). Also avoid preceding numbers with a 0, since C will then interpret the number as an octal number; e.g. 010 = 8.0b010 == 2