wiki:howto/bitfields_in_microblaze

Version 2 (modified by chunter, 9 years ago) (diff)

--

Using Bit-Fields in a MicroBlaze C Project

We use a very useful C programming tool in the 802.11 Reference Design known as a Bit-Field. Bits are not individually addressable in C. When unaligned access is enabled in a processor, the minimum addressable unit of data is a byte. Bit-fields provide a useful way of interpreting the bits that make up larger type definitions. They can help abstract away the low level bit shifts and bit masks needed for bit manipulation. This document is a tutorial on how to use bit-fields in MicroBlaze C projects.

A typical situation where you might see a bit-field is a definition like the following:

/* 
 *  This is an example of a simple 1-byte bitfield with three members: A, B, and C
 *
 *  Bit mask:
 *  MSB _ _ _ _ _ _ _ _ LSB
 *      C|-----B-----|A
 *
 *      A, C are 1-bit flags.
 *      B is a 6-bit integer.
 *
 */

typedef union{
    u8 raw_value;
    struct __attribute__ ((__packed__)){
        unsigned A          :1;  //b[0]
        unsigned B          :6;  //b[6:1]
        unsigned C          :1;  //b[7]
    };
} bitfield_example_type;

The above type definition defines a bit-field named bitfield_example_type. There are four important features to notice in the above syntax:

  • A union is used between to designate that raw_value and the proceeding struct occupy the same space.
  • The __attribute__ ((__packed__))
  • By convention, raw_value is the same size as the proceeding struct (a single byte). If the code does not need to interpret the individual bits in the bit-field, it can instead access the fully byte itself by using raw_value.
  • In the struct definition, the :X notation is used to tell the compiler that the element is X bits wide.

Example: Register Access

Example: Interpretation of Byte Array