Typedef Union For Different Definitions Of The Same Memory Locations


typedef union _SYSTEM_CONFIGURATION_TYPEDEF
{
    DWORD dw[25];
    WORD w[50];
    BYTE b[100];
} SYSTEM_CONFIGURATION_TYPEDEF;

SYSTEM_CONFIGURATION_TYPEDEF system_config_buffer;

	system_config_buffer.b[0] = 1;
	system_config_buffer.b[1] = 2;
	system_config_buffer.b[2] = 3;
	system_config_buffer.b[3] = 4;
	system_config_buffer.b[4] = 5;
	//Will give:
	//system_config_buffer.w = 0x0201
	//system_config_buffer.dw = 0x04030201

Typedef Struct


typedef struct _TEST_HEADER
{
  WORD source_port;
  DWORD sequence_number;
  WORD window;
} TEST_HEADER;

Typedef Struct For A Buffer Of Different Registers In An Buffer


typedef struct _TEST_HEADER
{
	WORD source_port;
	DWORD sequence_number;

	union		//<<< You can also have unions inside a struct
	{
		struct
		{
			BYTE flag_fin	:1;
			BYTE flag_syn	:1;
			BYTE flag_rst	:1;
			BYTE flag_psh	:1;
			BYTE flag_ack	:1;
			BYTE flag_urg	:1;
			BYTE reserved	:2;
		} bits;
		BYTE byte;
	} flags;

	WORD window;
} TEST_HEADER;

A Union To Convert Float To Bytes And Bytes To Float


union FLOAT_BYTES
{
	float f;
	BYTE v[sizeof(float)];
};
//HOW TO USE:
//	FLOAT_BYTES my_value;
//	my_value.f = 0.1234;
//	BYTE x = my_value.v[0];

Handy Conversions



typedef union _MODBUS_ARRAY_TYPEDEF
{
    WORD w[(NV_MEMORY_LENGTH >> 1)];
    BYTE v[NV_MEMORY_LENGTH];
} MODBUS_ARRAY_TYPEDEF;

typedef union _FLOAT_BYTES
{
	float f;
	WORD w[2];
	BYTE v[4];
}FLOAT_BYTES;
//HOW TO USE:
//	FLOAT_BYTES my_value;
//	my_value.f = 0.1234;
//	BYTE x = my_value.v[0];

typedef union _DOUBLE_BYTES
{
	double d;
	WORD w[2];
	BYTE v[4];
}DOUBLE_BYTES;

typedef union _SIGNED_WORD_BYTES
{
	SIGNED_WORD sw;
	WORD w;
	BYTE v[2];
}SIGNED_WORD_BYTES;

Union and Struct combined


#define	NV_MEMORY_LENGTH			20
typedef struct _NON_VOLATILE_STRUCT
{
	union
	{
		struct
		{
			uint32_t my_u32_val_1;
			uint32_t my_u32_val_2;
			uint16_t my_u16_val_1;
			//<<<Add others here
		} val;
		uint8_t b[NV_MEMORY_LENGTH];
	};
} NON_VOLATILE_STRUCT;
//non_volatile.val.
//non_volatile.b[]

NON_VOLATILE_STRUCT non_volatile;


	non_volatile.val.my_u32_val_1 = 0x12345678;
	non_volatile.b[0] = 0x12;

 

 

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.