C Language Bit-fields

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

Most variables in C have a size that is an integral number of bytes. Bit-fields are a part of a structure that don't necessarily occupy a integral number of bytes; they can any number of bits. Multiple bit-fields can be packed into a single storage unit. They are a part of standard C, but there are many aspects that are implementation defined. They are one of the least portable parts of C.

Syntax

  • type-specifier identifier : size;

Parameters

ParameterDescription
type-specifiersigned, unsigned, int or _Bool
identifierThe name for this field in the structure
sizeThe number of bits to use for this field

Remarks

The only portable types for bit-fields are signed, unsigned or _Bool. The plain int type can be used, but the standard says (§6.7.2¶5) … for bit-fields, it is implementation-defined whether the specifier int designates the same type as signed int or the same type as unsigned int.

Other integer types may be allowed by a specific implementation, but using them is not portable.



Got any C Language Question?