Now I am curious, [are flags] the only way bit-fields are used practically?
不,标志不是使用位字段的唯一方式.它们也可用于存储大于一位的值,尽管标志更为常见.例如:
typedef enum {
NORTH = 0,
EAST = 1,
SOUTH = 2,
WEST = 3
} directionValues;
struct {
unsigned int alice_dir : 2;
unsigned int bob_dir : 2;
} directions;
Do we need to use bit fields to save space?个
位字段确实节省了空间.它们还允许以一种更简单的方式设置不是字节对齐的值.我们可以使用与设置struct
中的字段相同的语法,而不是进行位移位和使用位操作.这提高了可读性.使用位字段,您可以编写
directions.alice_dir = WEST;
directions.bob_dir = SOUTH;
但是,要在一个int
(或其他类型)的空间中存储多个独立的值,而不使用位字段,您需要编写如下代码:
#define ALICE_OFFSET 0
#define BOB_OFFSET 2
directions &= ~(3<<ALICE_OFFSET); // clear Alice's bits
directions |= WEST<<ALICE_OFFSET; // set Alice's bits to WEST
directions &= ~(3<<BOB_OFFSET); // clear Bob's bits
directions |= SOUTH<<BOB_OFFSET; // set Bob's bits to SOUTH
可以说,提高位域的可读性比在各处节省几个字节更重要.
Why do we use int? How much space is occupied?
整个int
的空间被占用了.我们使用int
,因为在很多情况下,这并不重要.如果对于单个值,使用4字节而不是1或2字节,用户可能不会注意到.对于某些平台,大小确实更重要,您可以使用占用更少空间的其他数据类型(char
、short
、uint8_t
等).
As I understand only 1 bit is occupied in memory, but not the whole unsigned int value. Is it correct?个
不,那是不对的.即使你只使用其中的8位,整个unsigned int
位都将存在.