Archived

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

Access individual bits?

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Guest Anonymous Poster
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 this post


Link to post
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
}

Share this post


Link to post
Share on other sites