Difference between revisions of "Bitfields programming"

From Teknologisk videncenter
Jump to: navigation, search
m (added Category:C++ using HotCat)
m
Line 1: Line 1:
 
=C and C++ programming=
 
=C and C++ programming=
Example
+
In the example below the complete structure will live in 4 bytes on a 32 bit memorysystem.
 
<source lang=c>
 
<source lang=c>
 
#include <stdio.h>
 
#include <stdio.h>
  
void main( void ) {
 
 
struct display {
 
struct display {
 
     unsigned format : 1;  // 24 hour or 12 hour format
 
     unsigned format : 1;  // 24 hour or 12 hour format
 
     unsigned pm    : 1;  // PM and AM leds. If 12 hour format pm or am (pm=0 is am)
 
     unsigned pm    : 1;  // PM and AM leds. If 12 hour format pm or am (pm=0 is am)
     unsigned alarm  : 1;  // Alarm on/off LED.  
+
     unsigned alarm  : 1;  // Alarm on/off LED.
 
     unsigned digit1 : 4;  // Hour MSD 7 segment
 
     unsigned digit1 : 4;  // Hour MSD 7 segment
 
     unsigned digit2 : 4;  // Hour LSD 7 segment
 
     unsigned digit2 : 4;  // Hour LSD 7 segment
 
     unsigned digit3 : 4;  // Minute MSD 7 segment
 
     unsigned digit3 : 4;  // Minute MSD 7 segment
     unsigned digit3 : 4;  // minute LSD 7 segment
+
     unsigned digit4 : 4;  // minute LSD 7 segment
 +
    unsigned date  : 5;  // Date 1. to 31.
 +
    unsigned month  : 4;  // Month 1 to 12
 
};
 
};
 +
 +
void main(void) {
 +
        struct display d;
 +
        printf("Structure size: %i\n", (int) sizeof d);
 +
}
 
</source>
 
</source>
 
=Links=
 
=Links=

Revision as of 09:11, 26 August 2012

C and C++ programming

In the example below the complete structure will live in 4 bytes on a 32 bit memorysystem.

#include <stdio.h>

struct display {
    unsigned format : 1;   // 24 hour or 12 hour format
    unsigned pm     : 1;   // PM and AM leds. If 12 hour format pm or am (pm=0 is am)
    unsigned alarm  : 1;   // Alarm on/off LED.
    unsigned digit1 : 4;   // Hour MSD 7 segment
    unsigned digit2 : 4;   // Hour LSD 7 segment
    unsigned digit3 : 4;   // Minute MSD 7 segment
    unsigned digit4 : 4;   // minute LSD 7 segment
    unsigned date   : 5;   // Date 1. to 31.
    unsigned month  : 4;   // Month 1 to 12
};

void main(void) {
        struct display d;
        printf("Structure size: %i\n", (int) sizeof d);
}

Links