HOME

TheInfoList



OR:

A bit field is a
data structure In computer science, a data structure is a data organization, management, and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, ...
that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected. A bit field is most commonly used to represent integral types of known, fixed bit-width, such as single-bit Booleans. The meaning of the individual bits within the field is determined by the programmer; for example, the first bit in a bit field (located at the field's base address) is sometimes used to determine the state of a particular attribute associated with the bit field. Within
CPU A central processing unit (CPU), also called a central processor, main processor or just processor, is the electronic circuitry that executes instructions comprising a computer program. The CPU performs basic arithmetic, logic, controlling, a ...
s and other logic devices, collections of bit fields called flags are commonly used to control or to indicate the outcome of particular operations. Processors have a
status register A status register, flag register, or condition code register (CCR) is a collection of status flag bits for a processor. Examples of such registers include FLAGS register in the x86 architecture, flags in the program status word (PSW) register in ...
that is composed of flags. For example if the result of an addition cannot be represented in the destination an
arithmetic overflow Arithmetic () is an elementary part of mathematics that consists of the study of the properties of the traditional operations on numbers—addition, subtraction, multiplication, division, exponentiation, and extraction of roots. In the 19th ce ...
is set. The flags can be used to decide subsequent operations, such as conditional jump instructions. For example, a JE ... (Jump if Equal) instruction in the
x86 assembly language x86 assembly language is the name for the family of assembly languages which provide some level of backward compatibility with CPUs back to the Intel 8008 microprocessor, which was launched in April 1972. It is used to produce object code for t ...
will result in a jump if the Z (zero) flag was set by some previous operation. A bit field is distinguished from a bit array in that the latter is used to store a large set of bits indexed by integers and is often wider than any integral type supported by the language. Bit fields, on the other hand, typically fit within a machine
word A word is a basic element of language that carries an objective or practical meaning, can be used on its own, and is uninterruptible. Despite the fact that language speakers often have an intuitive grasp of what a word is, there is no conse ...
, and the denotation of bits is independent of their numerical index.


Implementation

Bit fields can be used to reduce memory consumption when a program requires a number of integer variables which always will have low values. For example, in many systems storing an integer value requires two bytes (16-bits) of memory; sometimes the values to be stored actually need only one or two bits. Having a number of these tiny variables share a bit field allows efficient packaging of data in the memory. In C and C++, native implementation-defined bit fields can be created using unsigned int, signed int, or (in C99) _Bool. In this case, the programmer can declare a structure for a bit field which labels and determines the width of several subfields. Adjacently declared bit fields of the same type can then be packed by the compiler into a reduced number of words, compared with the memory used if each 'field' were to be declared separately. For languages lacking native bit fields, or where the programmer wants control over the resulting bit representation, it is possible to manually manipulate bits within a larger word type. In this case, the programmer can set, test, and change the bits in the field using combinations of masking and
bitwise operations In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral (considered as a bit string) at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic opera ...
.


Examples


C programming language

Declaring a bit field in C and
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
: // opaque and show #define YES 1 #define NO 0 // line styles #define SOLID 1 #define DOTTED 2 #define DASHED 3 // primary colors #define BLUE 0b100 #define GREEN 0b010 #define RED 0b001 // mixed colors #define BLACK 0 /* 000 */ #define YELLOW (RED , GREEN) /* 011 */ #define MAGENTA (RED , BLUE) /* 101 */ #define CYAN (GREEN , BLUE) /* 110 */ #define WHITE (RED , GREEN , BLUE) /* 111 */ const char* colors = ; // bit field box properties struct BoxProps ; The layout of bit fields in a C struct is implementation-defined. For behavior that remains predictable across compilers, it may be preferable to emulate bit fields with a primitive and bit operators: /* Each of these preprocessor directives defines a single bit, corresponding to one button on the controller. Button order matches that of the Nintendo Entertainment System. */ #define KEY_RIGHT 0b00000001 #define KEY_LEFT 0b00000010 #define KEY_DOWN 0b00000100 #define KEY_UP 0b00001000 #define KEY_START 0b00010000 #define KEY_SELECT 0b00100000 #define KEY_B 0b01000000 #define KEY_A 0b10000000 int gameControllerStatus = 0; /* Sets the gameControllerStatus using OR */ void KeyPressed( int key ) /* Clears the gameControllerStatus using AND and ~ (binary NOT)*/ void KeyReleased( int key ) /* Tests whether a bit is set using AND */ int IsPressed( int key )


Processor status register

The
status register A status register, flag register, or condition code register (CCR) is a collection of status flag bits for a processor. Examples of such registers include FLAGS register in the x86 architecture, flags in the program status word (PSW) register in ...
of a processor is a bit field consisting of several flag bits. Each flag bit describes information about the processor's current state. As an example, the status register of the
6502 The MOS Technology 6502 (typically pronounced "sixty-five-oh-two" or "six-five-oh-two") William Mensch and the moderator both pronounce the 6502 microprocessor as ''"sixty-five-oh-two"''. is an 8-bit microprocessor that was designed by a small te ...
processor is shown below: {, class="wikitable" , + 6502 status register , - ! Bit 7 !! Bit 6 !! Bit 5 !! Bit 4 !! Bit 3 !! Bit 2 !! Bit 1 !! Bit 0 , - , Negative flag , , oVerflow flag , , - , , Break flag , , Decimal flag , , Interrupt-disable flag , , Zero flag , , Carry flag These bits are set by the processor following the result of an operation. Certain bits (such as the Carry, Interrupt-disable, and Decimal flags) may be explicitly controlled using set and clear instructions. Additionally, branching instructions are also defined to alter execution based on the current state of a flag. For an instance, after an ADC (Add with Carry) instruction, the BVS (Branch on oVerflow Set) instruction may be used to jump based on whether the overflow flag was set by the processor following the result of the addition instruction.


Extracting bits from flag words

A subset of flags in a flag field may be extracted by
AND or AND may refer to: Logic, grammar, and computing * Conjunction (grammar), connecting two words, phrases, or clauses * Logical conjunction in mathematical logic, notated as "∧", "⋅", "&", or simple juxtaposition * Bitwise AND, a boolea ...
ing with a
mask A mask is an object normally worn on the face, typically for protection, disguise, performance, or entertainment and often they have been employed for rituals and rights. Masks have been used since antiquity for both ceremonial and pra ...
. A large number of languages support the shift operator (<<) where 1 << n aligns a single bit to the nth position. Most also support the use of the
AND or AND may refer to: Logic, grammar, and computing * Conjunction (grammar), connecting two words, phrases, or clauses * Logical conjunction in mathematical logic, notated as "∧", "⋅", "&", or simple juxtaposition * Bitwise AND, a boolea ...
operator (&) to isolate the value of one or more bits. If the status-byte from a device is 0x67 and the 5th flag bit indicates data-ready. The mask-byte is 2^5 = 0x20.
AND or AND may refer to: Logic, grammar, and computing * Conjunction (grammar), connecting two words, phrases, or clauses * Logical conjunction in mathematical logic, notated as "∧", "⋅", "&", or simple juxtaposition * Bitwise AND, a boolea ...
ing the status-byte 0x67 (0110 0111 in binary) with the mask-byte 0x20(0010 0000 in binary) evaluates to 0x20. This means the flag bit is set i.e the device has data-ready. If the flag-bit had not been set, this would have evaluated to 0 i.e. there is no data available from the device. To check the nth bit from a variable v, perform the operation: bool nth_is_set = (v & (1 << n)) != 0; bool nth_is_set = (v >> n) & 1;


Changing bits in flag words

Writing, reading or toggling bits in flags can be done only using the OR, AND and NOT operations – operations which can be performed quickly in the processor. To set a bit, OR the status byte with a mask byte. Any bits set in the mask byte or the status byte will be set in the result. To toggle a bit,
XOR Exclusive or or exclusive disjunction is a logical operation that is true if and only if its arguments differ (one is true, the other is false). It is symbolized by the prefix operator J and by the infix operators XOR ( or ), EOR, EXOR, , ...
the status byte and the mask byte. This will set a bit if it is cleared or clear a bit if it is set.


See also

*
Binary code A binary code represents text, computer processor instructions, or any other data using a two-symbol system. The two-symbol system used is often "0" and "1" from the binary number system. The binary code assigns a pattern of binary digits, als ...
* Bitboard, used in chess and similar games * Bit array (or bit string) *
Word (computer architecture) In computing, a word is the natural unit of data used by a particular processor design. A word is a fixed-sized datum handled as a unit by the instruction set or the hardware of the processor. The number of bits or digits in a word (the ''word ...
*
Mask (computing) In computer science, a mask or bitmask is data that is used for bitwise operations, particularly in a bit field. Using a mask, multiple bits in a byte, nibble, word, etc. can be set either on or off, or inverted from on to off (or vice versa) i ...
* Program status word *
Status register A status register, flag register, or condition code register (CCR) is a collection of status flag bits for a processor. Examples of such registers include FLAGS register in the x86 architecture, flags in the program status word (PSW) register in ...
* FLAGS register (computing) *
Control register A control register is a processor register which changes or controls the general behavior of a CPU or other digital device. Common tasks performed by control registers include interrupt control, switching the addressing mode, paging control, ...


References


External links


Explanation from a book

Description from another wiki

Use case in a C++ guide

C++ libbit bit libraryalternative URL


Several snippets of C code manipulating bit fields Bit data structures Articles with example C code