Is there a way to address a single bit in C?

Ban Piao picture Ban Piao · Apr 10, 2012 · Viewed 12k times · Source

I've done some researching on bit addressable microcontrollers. The only one that came across in my path is the Intel MCS-51(wiki page) which is still used very commonly today... I was wondering if you can directly address a bit in C, for example on the SFR region wiki 8051 memory architecture.

The bits that I address in the SFR, are they bit addressed directly, or is it a bitwise operation in a bitfield that is byte addressed or is it something else completely?

Specifically, from here: Check if a single bit is set, it looks like the bit is directly manipulated with a MOV, I'm wondering if this is possible in C (with extensions) or does it only look like bitwise operation, but in the background there are some compiler stuff that uses bytes only?

As a follow up question, are there any bit addressable modern processors?

Answer

ixe013 picture ixe013 · Apr 10, 2012

In plain C (without any extensions, whatever they may be), you can declare a variable as a bit field. It can save a lot of typing and is less error prone.

Here is an example program. It declares a bit field with an union with a regular type of the same size.

#include <stdio.h>

int main(int argc, char *argv[])
{
    typedef struct 
    {
        union
        {
            struct {
                int bit0:1;
                int bit1:1;
                int bit2:1;
                int bit3:1;
                int bit4:1;
                int bit5:1;
                int bit6:1;
                int bit7:1;
            };
            unsigned char byte;
        };
    } EigthBits;

    EigthBits b;

    b.byte = 0;
    printf("Will be 0 ==> %d\n", b.byte);

    b.bit4 = 1;
    printf("Will be 16 ==> %d\n", b.byte);
}

Will print this output :

    Will be 0 ==> 0
    Will be 16 ==> 16

It is usefull to set values to individual bit on a control register, for example. You can set more bits (like int two_bits:2;) to suit your needs.