liveBook · Manning

Bit field

As explained in Modern C, Third Edition

A bit-field is a C structure or union member declared with a specified number of bits rather than a complete storage-unit width.

A bit field declares a structure or union member with a specified bit width after a colon. Successive fields may share larger storage units, reducing padding while remaining accessible through ordinary member expressions and assignments. section 6.3.4

Compact calendar fields

The declarations in struct tib assign widths such as 6 bits for seconds, 5 for hours, and 1 for the daylight-saving flag. This traditional version is marked erroneous: an int bit-field may be signed or unsigned depending on the implementation. A safer alternative gives fields explicit types, as in struct tbi; its members remain usable in expressions such as x.tbi_min < 60.

struct tbi {
  unsigned _BitInt(6) tbi_sec  :6; // Seconds after the minute [0, 60]
  unsigned _BitInt(6) tbi_min  :6; // Minutes after the hour   [0, 59]
  unsigned _BitInt(5) tbi_hour :5; // Hours since midnight     [0, 23]
  unsigned _BitInt(5) tbi_mday :5; // Day of the month         [1, 31]
  unsigned _BitInt(4) tbi_mon  :4; // Months since January     [0, 11]
  signed              tbi_year;    // Years since 1900
  unsigned _BitInt(3) tbi_wday :3; // Days since Sunday        [0, 6]
  unsigned _BitInt(9) tbi_yday :9; // Days since January       [0, 365]
  bool                tbi_isdst:1; // Daylight Saving Time flag
};

Compare explicitly typed widths for calendar values, including _BitInt fields and a bool flag. section 6.3.4

How Modern C, Third Edition covers it

How deep it goes
Explains declaration syntax, compiler coalescing, member access, storage estimates, and signedness hazards, but not complete layout rules.
Examples
Uses calendar-style fields for seconds, minutes, hours, dates, weekdays, year, and daylight-saving status.
What it assumes
Assumes familiarity with C structures, members, integer types, and designated initializers.
What you can do after
Build it from scratch by declaring compact C structure fields, accessing them normally, and checking signedness choices.
How it connects
Connects bit fields with structures, unions, structure padding, designated initializers, integer types, and portability.

Also explained in

Compare how 2 books explain bit field →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.