#### Archived

This topic is now archived and is closed to further replies.

# Access individual bits?

This topic is 5618 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I''m making a driving game and to send the status to the server i would like to use only a single byte. How do i access each bit turning 1 byte into 8 booleans? I could do it where every possible combination had a value between 0-256 but no thanks, there has to be a better way.

##### Share on other sites
C/C++

bit = 1<<bitnum; // Convert bit number to bit mask
x = x | bit; // Set bit true
x = x & ~(bit); // Set bit to false
x ^= bit; // Toggle bit
x & bit // Determine if bit is true
!(x & bit) // Determine if bit is false
x&(-x) // Returns the lowest set bit in x

##### Share on other sites
Using bit logic:

byte AND 1 = bit 0
byte AND 2 = bit 1
byte AND 4 = bit 2
byte AND 8 = bit 3
byte AND 16 = bit 4
byte AND 32 = bit 5
byte AND 64 = bit 6
byte AND 128 = bit 7

So, if you want to check if bit 4 is set, you would use something like:

if (byte AND 16) != 0 then do something

As a C/C++ example:

if (byte & 16)
{
do something
}

Thanx.

1. 1
Rutin
29
2. 2
3. 3
4. 4
5. 5

• 13
• 13
• 11
• 10
• 14
• ### Forum Statistics

• Total Topics
632961
• Total Posts
3009491
• ### Who's Online (See full list)

There are no registered users currently online

×