Access individual bits?
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.
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
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
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
}
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
}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement