Skip to main content
Visitor II
September 2, 2005
Question

Bitfield operation in C.

  • September 2, 2005
  • 3 replies
  • 891 views
Posted on September 02, 2005 at 14:58

Bitfield operation in C.

    This topic has been closed for replies.

    3 replies

    ongth60Author
    Visitor II
    August 24, 2005
    Posted on August 25, 2005 at 01:14

    Hi guys,

    I would like some advise if its possible to declare a variable of 24 bits and manipulate each single bit like setting bits?

    Rgrds,

    ongth60

    ongth60Author
    Visitor II
    September 2, 2005
    Posted on September 02, 2005 at 02:30

    Hi,

    This is using the GPIO as an example, mayb i dun understand how do i use it as a general variable where the size is of the variable is 8 bit and i can manipulate each single bit and when i were to store, i can store the whole byte all together, like creating my own settings:

    struct{

    u8 Regular_Reporting_Time : 3;

    u8 Non_Violation_SMS_Enable : 1;

    u8 Vibration_Enable : 1;

    u8 Smart_Powersave_Enable : 1;

    u8 FLEET_Type_Enable : 1;

    u8 Voice_Call_Enable : 1;

    }Byte3_Setting;

    Regular_Reporting_Time = 0x04;

    Vibration_Enable = 0x01;

    EEPROM_byte_write(Byte3_Setting);

    Rgrds,

    ongth60

    Visitor II
    September 2, 2005
    Posted on September 02, 2005 at 14:58

    ongth60,

    You first have to allocate a variable for a Byte3_Setting structure. Then you can access the bit fields through normal structure member access (i.e. dot notation)...for example

    void SaveSettings(void)

    {

    struct Byte3_Setting mySettings;

    mySettings.Regular_Reporting_Time = 0x04;

    mySettings.Vibration_Enable = 0x01;

    EEPROM_byte_write(Byte3_Setting);

    }

    This example isn't particularly practical, but that's how you can use your structure.

    In a more practical usage you would probably want to allocate your variable somewhere else and pass a pointer along with settings to fill in but remember then you would access the members using the -> operator like:

    void SaveSettings(struct Byte3_Setting *pSettings, int reportingTimeValue, int vibrationEnabled)

    {

    pSettings->Regular_Reporting_Time = reportingTimeValue;

    pSettings->Vibration_Enable = vibrationEnabled;

    EEPROM_byte_write(*pSettings);

    }

    Also check your compiler documentation to make sure you understand how it handles bit-fields and structure packing as this can sometimes be a problematic area.

    Hope this helps.

    Ryan.