struct

Hi all,

If i have the following code:

struct obj
{
bool var0;
bool var1;
bool var2;
bool var3;
.... // more member variable, i don,t want implement it as array
};

how can i convert the member variable of this struct ot bit stream with min. code??

i apreciate each suggestion..
Well, since you're not using an array, there's only one way:
1
2
3
4
5
6
7
8
9
10
unsigned x;
x=var0;
x<<=1;
x=var1;
x<<=1;
x|=var2;
x<<=1;
x|=var3;
x<<=1;
//... 
Hi @helios,

may you clerify your suggestion a bit more.. i could not implement it as you said..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25


struct obj
{
bool var0;
bool var1;
bool var2;
bool var3;
.... // more member variable, i don,t want implement it as array
};

int main{

Obj Obj;
Obj.var0 = 0;
Obj.var0 = 1;
Obj.var0 = 0;
Obj.var0 = 1;


unsigend t = 0;

//  how can i continue it ?

}


i am a bit stuck here..

thanks
Last edited on
What helios said is
1
2
3
4
unsigned bitstream = 0;
bitstream <<= 1;//shifts bitstream left, so that there is a new first bit
bitstream |= var0;//bitwise OR sets first bit in bit stream if var0 is set
//repeat the last two lines for each var 


Now, even though it is not an official array, it is a sequense, so you can treat it almost as an array.
1
2
3
4
5
6
bool* var = &var0;
unsigned bitstream = 0;
for(int i = 0; i < /*...*/; i++){
    bitsrteam <<= 1;
    bitstream |= var[i];
}
@hamsterman: what do you mean with this code:
1
2
3
4
5
6
bool* var = &var0;
unsigned bitstream = 0;
for(int i = 0; i < /*...*/; i++){
    bitsrteam <<= 1;
    bitstream |= var[i];
}



In this way it will never be executable!

any Suggestion...

I mean that there is little difference between bool var[] and bool var0, var1, var2, ....

In this way it will never be executable!
Why not? (of course instead of /*...*/ there should be the number of variables you have)

Edit: it sholud be Obj.var0, if you want to put this code in main(), though a member function would make sense.
Last edited on
Topic archived. No new replies allowed.