Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

8051

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?

like image 466
Ban Piao Avatar asked Apr 10 '12 02:04

Ban Piao


2 Answers

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.

like image 78
ixe013 Avatar answered Sep 18 '22 19:09

ixe013


This is not uncommon. For example, SDCC (Small Device C Compiler) is a popular compiler for MCS-51. You'll find the manual here. The most relevant section is 3.4.1, it describes the language extensions for MCS-51:

3.4.1.6 __bit

This is a data-type and a storage class specifier. When a variable is declared as a bit, it is allocated into the bit addressable memory of 8051, e.g.:

 __bit test_bit;

Writing 1 to this variable generates the assembly code:

 D2*00 setb _test_bit

The bit addressable memory consists of 128 bits which are located from 0x20 to 0x2f in data memory. Apart from this 8051 specific storage class most architectures support ANSI-C bitfields4. In accordance with ISO/IEC 9899 bits and bitfields without an explicit signed modifier are implemented as unsigned.

like image 40
Hans Passant Avatar answered Sep 17 '22 19:09

Hans Passant