union and bits

  • Thread starter chandra sekhar nunna
  • Start date
C

chandra sekhar nunna

Hello All,

typedef union
{
int m_4ByteData;
char m_8bitData[4];
}data;

data conv;
conv.m_4ByteData = 1000;

I am using above union i am getting all the individual 8 bits ( 8 * 4 =
32 bits for int ). How to get the int value ( m_4ByteData) using
m_8bitData[4].

Thanks in advance
Chandra-
 
O

olaf

Just access the structure

typedef union
{
int m_4ByteData;
char m_8bitData[4];
}data;

data conv;
conv.m_4ByteData = 1000;
printf("m_8bitData = %d %d %d %d\n",
conv.m_8bitData[0],
conv.m_8bitData[1],
conv.m_8bitData[2],
conv.m_8bitData[3]);

It has the same memmory attached to it

so &(conv.m_4ByteData) == &(conv.m_8bitData[0]) is always TRUE.

Greetings Olaf
 
C

chandra sekhar nunna

Hi,

Any idea how round double values using the same concept.

Bye
Chandra-
Just access the structure

typedef union
{
int m_4ByteData;
char m_8bitData[4];
}data;

data conv;
conv.m_4ByteData = 1000;
printf("m_8bitData = %d %d %d %d\n",
conv.m_8bitData[0],
conv.m_8bitData[1],
conv.m_8bitData[2],
conv.m_8bitData[3]);

It has the same memmory attached to it

so &(conv.m_4ByteData) == &(conv.m_8bitData[0]) is always TRUE.

Greetings Olaf

chandra sekhar nunna said:
Hello All,

typedef union
{
int m_4ByteData;
char m_8bitData[4];
}data;

data conv;
conv.m_4ByteData = 1000;

I am using above union i am getting all the individual 8 bits ( 8 * 4 =
32 bits for int ). How to get the int value ( m_4ByteData) using
m_8bitData[4].

Thanks in advance
Chandra-
 
D

Dan Pop

In said:
Hello All,

typedef union
{
int m_4ByteData;
char m_8bitData[4];
}data;

data conv;
conv.m_4ByteData = 1000;

I am using above union i am getting all the individual 8 bits ( 8 * 4 =
32 bits for int ). How to get the int value ( m_4ByteData) using
m_8bitData[4].

Put the stuff into m_8bitData[4] and read the value of m_4ByteData.
In theory, this invokes undefined behaviour, in practice, it works.

You may want to replace the magical constant 4 by sizeof(int) and to
use the type unsigned char for m_8bitData[4].

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Union and strict aliasing 4
Portability issues (union, bitfields) 7
union, strcpy and main() 10
UNION global variabl initialize 10
Query abt union 23
Shifting bits 31
array of bits 31
Union In C 4

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top