-
Bit manipulation
can anyone please tell me how to return a bit for this problem
address variable size is 3 i.e 001 or 110 then it has to generate the corresponding bit from a 8 bit vector11111111 corresponding to the address bit
eg
address is 101
vector is 10101100
101 is 5 so it should return 5th bit i.e 0 in this case
void main()
{
const unsigned uN = 3;
const unsigned u2_to_N = 2 * 2 * 2;
CBooleanDataset MultiplexerDataset(uN + u2_to_N);
CColumnVector<bool> InputVector(uN + u2_to_N);
bool bOutput;
for(unsigned i = 0; i <= u2_to_N; i++)
{
the thing is later i would later should be able to increase n for bigger problems
-
I'm not sure I understand the assignment, but to check bit-n, you can initialize your "mask" variable to one, and then bit-shift-left n-1 positions.
Then, perform a bitwise-AND to test the unknown bit. If the result is zero, your unknown bit is zero.
Bits are counted right to left, starting with bit zero which has a value (wieght) of 1. The "5th" bit would be bit-4. You'll be ANDing with 16 (base 10) or 0001 0000 (binary). So if you are testing bit-4, your mask is 16.
This all gets bit more difficult if your input is actually in binary. If your input is hex or decimal, and you never have to "see" the binary format, it's much easier.
P.S. You forgot to use code tags. Look above where it says "Posting Code? Read This First!"
-
There's some bit shifting notes here that may help you.
-
bitset?????
I didnīt understand your problem very well, but remember that you always can use the C++ template bitset . I donīt know if this solve your problem... if you donīt know how to use bitfield, I attached the entire Borlandīs documentation for bitset.
-
Code:
bool GetNthBit(char Flags, int N)
{
if(Flags & (1 << N)) return true;
else return false;
}
N is an integer value 0 - 7. Of course you can change char to something else, say int and make N 0 - 31.
-
Thanks magos
I am replying to my own problem and open to any more new ideas
.i have got some idea
if speed is very important then i could make it do something like this:
create an array
unsigned int *p = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80}
and the function now becomes
bool GetNthBit(char Flags, int N)
{
if(Flags & *(p+N) ) return true;
else return false;
}
which may be faster because no shifts are required.
and i could remove the need for the function and do it inline because in C and C++ zero is false and non-zero is true so this would then
reduce to:
(Flags & *(p+N)
removing the need for an if test