Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 223
  • Last Modified:

unions: multiple inputs (second input overwrites first?)

Hi, i'm doing a project for my class and can't seem to figure this out.

The first part is pretty simple. We simply had to write a program in C with a union with these conditions

union numType
{
      float f;
      unsigned int ui;
};
union numType u;

and input a number as a float and print out the binary in 32bit representation of it as an unsigned integer using a decimal to binary converter function. However, we had to split the binary up for the signed bit, exponent (excess 127), and the fractional part or mantisa.

Now, the second part where I have a problem. We have to get the user to input 2 short integers and display them in 32bit binary representation just like the first part. In addition, we also have to do it for 2 unsigned short ints and an array of 4 characters in 32bit. So using the union:

union numType
{
      short int s1,s2;
      unsigned short int us1,us2;
      char arry[3];
      unsigned char arryc[3];      
};

I understand how to do this and it's supposed to be simple right? However, when I get the user to input 2 short integers the second one overwrites the first one. I'm going about this with a basic:

      printf("Please enter 2 short integer numbers, 0 to exit ");
      scanf("%d%d",&u.s1,&u.s2);

am I doing something wrong here, why can't I input both values into the union? our teacher even said that is how you setup the union, but there must be something I'm doing wrong with the way i'm trying to input the values?
0
zennx
Asked:
zennx
1 Solution
 
sunnycoderCommented:
Hi zennx,

Your union should be

union numType
{
     short int s[2];
     unsigned short int us[2];
     char arry[4];
     unsigned char arryc[4];    
};

I hope this should enumerate what you were doing wrong

1. arr[3] is an array of 3 elements and not 4 ... You need 4 characters
2. Concept of union is that storage corresponding to largest elements is assigned and reading in a different element will overwrite the previous one ... Since you need to have two shorts at one instance, it is imperative that you have enough storage in the union to store 2 shorts at the same time or you can use a dirtier method and have atleast a component which can hold two shorts and do the packing and unpacking into that element on your own.

cheers
sunnycoder
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now