1. ## Can't figure out!

I need to improve this program by using union and bit fields.I do not know to apply it in my program.
I hope you guys will be able to help me clear my doubt. Thanks!

#include <stdio.h>
#include <conio.h>
#include <dos.h>

// Channel1 "00001 0 [00]" :0x08 /0x48 /0x88 /0xc8
// Channel2 "00001 0 [01]" :0x09 /0x49 /0x89 /0xc9
// Channel3 "00001 0 [10]" :0x0A /0x4a /0x8a /0xca
// Channel4 "00001 0 [11]" :0x0b /0x4b /0x8b /0xcb
// Channel5 "00001 1 [00]" :0x0C /0x4c /0x8c /0xcc
// Channel6 "00001 1 [01]" :0x0D /0x4d /0x8d /0xcd
// Channel7 "00001 1 [10]" :0x0E /0x4e /0x8e /0xce
// Channel8 "00001 1 [11]" :0x0F /0x4f /0x8f /0xcf

.................................................. ........
This portion is the part which needs improvement.

if(x==1) //Select which board.
outportb(0x315, 0x08 + (r - 1)); //Select which channel.

if(x==2)
outportb(0x315, 0x48 + (r - 1));

if(x==3)
outportb(0x315, 0x88 + (r - 1));

if(x==4)
outportb(0x315, 0xc8 + (r - 1));
.................................................. ........

2. To my knowledge bitfields are about as expensive as it gets when it comes to this sort of thing so if efficiency is the goal then don't use them. You can just use a structure that is wrapped in a union so that it has a certain alignment.

Code:
```union force_alignment_union {
struct {
unsigned short a, b, c, d;
} data;
short dummy; //don't play with this member
};```
This may actually be more expensive then what you were doing in the first place but it will certainly look cleaner. You could also use an array or a pointer to an array of unsigned shorts with four elements. From what I see you may be doing this the best way already.

3. One more thing about the bitfield approach (another reason you don't want to use it).

Code:
```/*if you decide you are going to do this despite what I've been saying at least you have an example of how */

struct bf {
unsigned short a : 16;
unsigned short b : 16;
unsigned short c : 16;
unsigned short d : 16;
};```
Okay, the biggest pitfall here is that the way the bits are ordered is machine dependant. The a member is the first 16 bits on some machines while on others it is the last 16 bits.

In your sample code your structure is already on a 32-bit boundary so you could just do this:

Code:
```struct whatever{
unsigned short a, b, c, d;
};```
There won't be any additional padding on the structure since it is 64 bits in size. So even on a 64-bit machine you are good to go. On a 16-bit machine this is also okay. So you may want to stick with the simple structure.

4. Hi Master 5001,1st thanks for your relpy.

I will really appreciate if u can explain to me in a simpler form, as I'm not very gd in programming. I don't quite undestand your 2nd post.