Friday, January 16, 2009

About Bit Field in C/C++

In the C/C++, 
usually we use the "Bit Field" to optimize code or communicate with other process.
What is the Bit Filed?

I have attached "Example Code".

Example code

// Test Code, Bit Field
// ----------------------------------
{
 #define u8 unsigned char

 #define FILL_STRUCT1 u8:0; u8:8; u8:0;
 #define FILL_STRUCT2 u8:0; u8:8; u8:8; u8:0;
 #define FILL_STRUCT3 u8:0; u8:8; u8:8; u8:8; u8:0;

 typedef struct tag_SIMCommand {
 u8 Class;
 u8 Instruction;
 u8 P1;
 u8 P2;
 u8 P3;
 FILL_STRUCT3 // Bit Field
 u8 CData[8];
 } SIMCommandType;

 SIMCommandType SIMCommand;

 memset(&SIMCommand, 0xFF, sizeof(SIMCommandType));
 memset(&SIMCommand, 0x00, sizeof(SIMCommandType));

 // SELECT
 SIMCommand.Class = 0xA0;
 SIMCommand.Instruction = 0xA4;
 SIMCommand.P1 = 0x00;
 SIMCommand.P2 = 0x00;
 SIMCommand.P3 = 0x02;
 memset(SIMCommand.CData, 0xFF, sizeof(u8)*8);
}
// ----------------------------------

// Real Memory, Dump 1
// ----------------------------------
0012F3B0  A0 A4 00 00  
0012F3B4  02 00 00 00  
0012F3B8  FF FF FF FF  
0012F3BC  FF FF FF FF  
// ----------------------------------

// Test Code, Bit Field
// ----------------------------------
{
 #define u8 unsigned char

 #define FILL_STRUCT1 u8:0; u8:8; u8:0;
 #define FILL_STRUCT2 u8:0; u8:8; u8:8; u8:0;
 #define FILL_STRUCT3 u8:0; u8:8; u8:8; u8:8; u8:0;

 typedef struct tag_SIMCommand {
 u8 Class:4;
 u8 Instruction:2;
 u8 P1:1;
 FILL_STRUCT1
 u8 P2:4;
 FILL_STRUCT2
 u8 P3:1;
 FILL_STRUCT3 // Bit Field
 u8 CData[8];
 } SIMCommandType;

 SIMCommandType SIMCommand;

 memset(&SIMCommand, 0xFF, sizeof(SIMCommandType));
 memset(&SIMCommand, 0x00, sizeof(SIMCommandType));

 // SELECT
 SIMCommand.Class = 0x0F;
 SIMCommand.Instruction = 0x03;
 SIMCommand.P1 = 0x01;
 SIMCommand.P2 = 0x0F;
 SIMCommand.P3 = 0x01;
 memset(SIMCommand.CData, 0xFF, sizeof(u8)*8);
}
// ----------------------------------

// Real Memory, Dump 2
// ----------------------------------
0012F39C  7F 00 0F 00  
0012F3A0  00 01 00 00  
0012F3A4  00 FF FF FF  
0012F3A8  FF FF FF FF  
0012F3AC  FF CC CC CC  
// ----------------------------------

If you have any question? Please let me know :-)

1 comment:

Unknown said...

몬 소리래ㅡㅡ;