# Bit access

• 12-02-2002
DjJeff
Bit access
Does anyone know an easy way to access individual the bits of, say, an unsigned int. I know there are methods that involve shifting the number and using bit-wise operators to determine the bit value. I would like to perform quick and repeatable access to the bits and don't want to destroy the data in the process of reading it. I assume there is some easy command using pointers.:confused:
• 12-02-2002
Polymorphic OOP
I prefer a bit more of an elegant solution

Code:

union ByteBitfield
{
unsigned char Value;
struct
{
bool Zero : 1,
One : 1,
Two : 1,
Three : 1,
Four : 1,
Five : 1,
Six : 1,
Seven : 1;
} Bits;
};

Now you can access the bits and the value quickly and easily without the nasty shifting anding and oring that's in Salem's example!

Code:

ByteBitfield MyData;

MyData.Value; // Gets you the value of the number

MyData.Bits.Zero; // Gives you "true" if the Zero bit is set to 1

MyData.Bits.One; // Gives you "true" if the One bit is set to 1

if( MyData.Bits.Three )
{
/* Do Something */
}

// You can also change the bit extremely easily

MyData.Bits.Three = true; // Set's bit Three to 1

MyData.Bits.Four = !MyData.Bits.Four; // Toggles bit Four

See! No nasty shifting, compilments, anding oring, or even comparisons!

Sorry to disagree with you Salem!
• 12-02-2002
Sang-drax
Quote:

Originally posted by Polymorphic OOP
I prefer a bit more of an elegant solution
I prefer an even more elegant solution :D

Code:

#include <bitset>
#inlude <iostream>
int main()
{
std::bitset<32> b = 0;
b[2] = 1;
b[5] = 1;

std::cout << b.to_ulong();
}

Use the standare headers as much as possible.
• 12-02-2002
Polymorphic OOP
Quote:

Originally posted by Sang-drax
Use the standare headers as much as possible.
The standard libraries take all the fun out of coding. They should die of gohnnoreah and rot in hell.

...yes, i know i spelled that horribly, horribly wrong
• 12-02-2002
Sang-drax
Using the bitset class would work, though.