Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

Manually save data in individual bits

Status
Not open for further replies.

beginner13

Newbie level 1
Joined
Mar 17, 2013
Messages
1
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,294
Hi! I'm a C beginner. I have questions, let say if I have a structure of message containing of Id, Length, and 3 bytes of data, and I want to manually saved in individual bits of data, how can I do that? I confused on how to use typedef struct and union. Below is the sample code:

typedef struct
{
uint8_t Id;
uint8_t Length;
uint8_t DataField[3];
}AA;


struct DataField
{
unsigned int b0:1;
unsigned int b1:1;
unsigned int b2:1;
unsigned int b3:1;
unsigned int b4:1;
unsigned int b5:1;
unsigned int b6:1;
unsigned int b7:1;
unsigned int b8:1;
unsigned int b9:1;
unsigned int b10:1;
unsigned int b11:1;
unsigned int b12:1;
unsigned int b13:1;
unsigned int b14:1;
unsigned int b15:1;
unsigned int b16:1;
unsigned int b17:1;
unsigned int b18:1;
unsigned int b19:1;
unsigned int b20:1;
unsigned int b21:1;
unsigned int b22:1;
unsigned int b23:1;
}u;

By the way, the DataField is declared as above. It's not necessary for a data to be 24 bits. It can be bit 0 - bit 8, it can be bit 10 - bit 15 and so on. So, for each case, I want to ignore the other bits.
 

What a union does is let the compiler know that you want to be able to access the same location in memory in more than one way. So, for a simple example, here's how I do this in my HD44780 LCD code:

Code:
union
{
	struct
	{
		unsigned bit0: 1;
		unsigned bit1: 1;
		unsigned bit2: 1;
		unsigned bit3: 1;
		unsigned bit4: 1;
		unsigned bit5: 1;
		unsigned bit6: 1;
		unsigned bit7: 1;
	};
	unsigned char LCD_dataByte;
}LCD_dataBits;

Then I can set all eight bits by going:

Code:
LCD_dataBits.LCD_dataByte = [a byte of data (e.g. a char or unsigned char)];

Or I can set an individual bit by going:

Code:
LCD_dataBits.bit0 = [1 or 0];
 

If you have a float value which is 4 bytes and int8 (1 byte) then you can use a Union like this.

Code C - [expand]
1
2
3
4
5
6
7
8
9
10
union{
   float myfloat;
   int8  bit[4];
 
}myUnion
 
myUnion.byte[0] = 4;
myUnion.byte[1] = 6;
myUnion.byte[2] = 8;
myUnion.byte[3] = 4;



myUnion.myfloat will be the the bytes 4, 8, 6, 4 converted to float representation.

Instead of float and byte use byte (char) variable and bit (bit / sbit) in union to access individual bits.

This might help https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top