bit class problem

Started by
5 comments, last by Kimmi 12 years, 9 months ago
Hi Gyus,
I have strange problem I cannot solve anyhow.
I have created a simple class storing bits:


class TEightBits
{
public:
bool bit0:1;
bool bit1:1;
bool bit2:1;
bool bit3:1;
bool bit4:1;
bool bit5:1;
bool bit6:1;
bool bit7:1;

TEightBits()
{
bit0=false;
bit1=false;
bit2=false;
bit3=false;
bit4=false;
bit5=false;
bit6=false;
bit7=false;
}

inline bool GetBit(unsigned short BitNum);
inline void SetBit(bool Bit, unsigned short BitNum);

};


When I set any bit in c++ main() function in the manner:

bool BIT=true;
TEightBits EB[3];
EB[1].bit1=BIT;

It works as I expected. But if I use function:

inline void SetBit(bool Bit, unsigned short BitNum)
{
switch (BitNum)
{
case 0: bit0=Bit;
case 1: bit1=Bit;
case 2: bit2=Bit;
case 3: bit3=Bit;
case 4: bit4=Bit;
case 5: bit5=Bit;
case 6: bit6=Bit;
case 7: bit7=Bit;
}
}

then all entries of a byte are set to true.
For example:


bool BIT=true;
TEightBits EB[3];
EB[1].SetBit(BIT,1);

Bits in EB[1] are in 11111111 instead of expected 01000000.
How to help this?

Thanks in advance for any help,
Regards,
Misery
Advertisement
It's probably because the switch/case statement is missing 'break's after each case and falling through.

However, what's wrong with just using an uint8_t and shifting bits into and out of it???

Jans.
OMG!
What a embarassing mistake :[
Thank You very much. Lately I am programming in scilab and i just forgot that in c/c++ there has to be break in switch expr.

I'm just playing to learn some new things. That's all.
Thanks again :]

Regards.
Have you thought about using the shift operator istead of using an bool-value for a single bit which is a waste of memory?

For instance:



class BitField
{
unsigned int m_BitField;
void set( unsigned int bitPos )
{
unsigned int val = 1 << bitPos;
m_BitField |= val;
}

bool isSet( unsigned int pos )
{
unsigned int val = 1 << bitPos;
if ( m_BitField & val )
return true;
else
return false;

}
};


Kimmi
A complicate solution may indicate a not understood problem.


[twitter]KimKulling[/twitter]

Have you thought about using the shift operator istead of using an bool-value for a single bit which is a waste of memory?

He's using bitfields which are already tightly packed, but automatically by the compiler instead of manually. Look at the definition of his class members in his original post.
Thank You all guys :]
Ah, I missed that. Thanks for that hint.

Kimmi
A complicate solution may indicate a not understood problem.


[twitter]KimKulling[/twitter]

This topic is closed to new replies.

Advertisement