Bit Fields in C In C, we can specify size (in bits) of structure and union members. The idea is to use memory efficiently when we know that the value of a field or group of fields will never exceed a limit or is within a small range. If storage is limited, we can go for bit-field. A special unnamed bit field of size 0 is used to force alignment on next boundary. For example consider the following program. For example, consider the following declaration of date without the use of bit fields. i can have pointers to 5-bit bit field members as they may not start at a byte boundary but i can new pointer structure assign to address of end of last bit only. i am declare 5 bit ascii code. please see my code :
#include <stdio.h>
// Space optimized representation of the date
struct date {
// d has value between 0 and 31, so 5 bits
// are sufficient
int d : 5;
// m has value between 0 and 15, so 4 bits
// are sufficient
int m : 4;
int y;
};
int main()
{
printf("Size of date is %lu bytes\n",
sizeof(struct date));
struct date dt = { 31, 12, 2014 };
printf("Date is %d/%d/%d", dt.d, dt.m, dt.y);
return 0;
}
Output:
Size of date is 8 bytes
Date is -1/-4/2014
The output comes out to be negative. What happened behind is that the value 31 was stored in 5 bit signed integer which is equal to 11111. The MSB is a 1, so it’s a negative number and you need to calculate the 2’s complement of the binary number to get its actual value which is what is done internally. By calculating 2’s complement you will arrive at the value 00001 which is equivalent to decimal number 1 and since it was a negative number you get a -1. A similar thing happens to 12 in which case you get 4-bit representation as 1100 which on calculating 2’s complement you get the value of -4. above code tell me my code and solution is correct? we can replace '\0' character and add space ascii code . i can use 5-bit instead 8-bit or 7-bit ascii code if my storage is very low. but in this situation i can used pointer for it.but problem is unsign and address in memory is sign .we can use sign address and tag it by last-bit and convert it to hex . please tell me my solution is correct or not?
CodePudding user response:
int d : 5
allows you to represent values between -16
and 15
, not between 0
and 31
.
int m : 4
allows you to represent values between -8
and 7
, not between 0
and 15
.
You need to use unsigned int
instead.