Is there a popular name for this bit-related expression? - bit-manipulation

Is there a popular name for this?:
#define ALL_BITS_SET(value, mask) ((value & mask) == mask)

Yes, it's called "contains", after the equivalent operation on sets.

In Smalltalk, we long have this Integer method
allMask: mask
"Treat the argument as a bit mask. Answer whether all of the bits that
are 1 in the argument are 1 in the receiver."
^mask = (self bitAnd: mask)

Signal masking | Bit Masking | Masking

Yeah, ALL_BITS_SET. It'a just a simple test to check whether value is equal to the bit combination represented by mask.

Related

C++ Read 1 Bit From Memory?

So looking in debugger I have found that i need to check if 1 bit is set to a certain value.
For example lets say at this memory address 0x12345 holds these four bytes 01008100, how would I go about checking if ONLY 8 is right there in that exact point? Sorry I am at a lack of words to use, I am not even sure how to really explain. But for example if I wanted to check if 8 was right there in that exact position in those bytes posted above my first guess would be to try something like this
if(*(char*)(0x12345 + 0x2) == 8)
{
//ok
}
But this obivously won't work because it will read the value as 0x81, I need to ONLY read if the 8 is there and ignore all other bits in front or behind it. Hopefully this question was worded in a way that at least someone will understand my question. Thank you for reading have a good day.
You can use a bitwise AND (&) to test individual bits, e.g.
if ((*(char*)(0x12345 + 0x2) & 0x80) == 0x80)
{
//ok
}
Note that the AND operation masks out the bits you are not interested in, e.g.
0x12345 + 0x2: 10000001 ; 0x81
AND with 0x80: 10000000 ; 0x80
It looks like you want to check if a particular bit in your 4 bytes value is set or not.
Assuming that you want to check the bit on a stream of bytes, and NOT on a 32 bits value, then I would use something similar to what you specified, but I would use a bitwise and operator:
if((*(std::uint8_t*)(0x12345 + 0x2) & 0x80) != 0)
{
// the bit is set
}
If you are trying to check the bit in a uint32 value, then you have to consider the endianness of the machine you are working with (high or low bit endian).
Fortunately, if you specify the right data type then the machine will take care of that for you.
// Note: 0x12345 is a fictional address, not properly aligned on some architectures
if((*(std::uint32_t*)0x12345 & 0x00008000) != 0)
{
// the bit is set
}

How to tell if two 8-bit chars are gray codes in c++?

The problem is to tell if two 8-bit chars are gray codes(differ only in 1 bit) in C++?
I found an elegant C++ solution:
bool isGray(char a, char b) {
int m = a ^ b;
return m != 0 && (m & (m - 1) & 0xff) == 0;
}
I was confused that what does the "& 0xff" do?
& 0xff extracts the 8 lowest bits from the resulting value, ignoring any higher ones.
It's wrong. The mistaken idea is that char is 8 bit.
It's also pointless. The presumed problem is that m can have more bits than char (true) so that "unnecessary" bits are masked off.
But m is sign-extended. That means the sign bit is copied to the higher bits. Now, when we're comparing x==0 we're checking whether all bits are zero, and with x & 0xff we're comparing if the lower 8 bits are zero. If the 8th bit of x is copied to all higher positions (by sign extension), then the two conditions are the same regardless of whether the copied bit was 0 or 1.

Bitfield mask/operations with optional items

I'm trying to find a way to handle several bitfield cases that include optional, required, and not allowed positions.
yy?nnn?y
11000001
?yyy?nnn
01110000
nn?yyy?n
00011100
?nnn?yyy
00000111
In these four cases, the ? indicates that the bit can be either 1 or 0 while y indicates a 1 is required and n indicates that a 0 is required. The bits to the left/right of the required bits can be anything and the remaining bits must be 0. Is there a masking method I can use to test if an input bit set satisfies one of these cases?
Absolutely, but of course it depends on how you represent the "templates".
For example, say you represent them as a pair (z, o) where z has a 1 for every bit that is allowed to be 0 and o has a 1 for every bit that is allowed to be 1 (as in the paper I linked to in the comments). Then to test x against it you could do:
if ((x | z) == -1 && (x & o) == x)
passes test
You could also represent the templates as a pair (mask, bits), where mask is a mask of all bits that have to match (ie 0 means ?, 1 means a fixed bit) and bits is the values of the fixed bits. Then you could test x like:
if ((x & mask) == bits)
passes test
That's in general. If your problem has a special form, as it does in your question, you could use specialized tests.
Try something like this (using C/C++ notation):
(input & mask) == mask && (input & ~(mask | mask<<1 | mask>>1)) == 0

Clear bit if another is set

Is there's a similar to:
if((bitmap & BIT_WATER) && (bitmap & BIT_FIRE)) bitmap &= ~BIT_FIRE
or
if(bitmap & BIT_WATER) bitmap &= ~BIT_FIRE
In a single statement using only bitwise operations, removing the need of a comparation (if)?
I totally mean that if two flag, each completly opposite to the other, are set clear one of them.
You can avoid the bitmap & BIT_FIRE in the first case, since bitmap &= ~BIT_FIRE; will do nothing to the bitmap if BIT_FIRE is not set.
There is no "set bit X if bit Y is set" in an arbitrary way.
Of course, if you KNOW that, say, BIT_FIRE is one bit higher than BIT_WATER, you could do bitmap &= ~(BIT_WATER << 1), which will clear the "one bit higher than BIT_WATER".
Probably premature optimization, but you could do
bitmap &= ~((bitmap & BIT_WATER) * (BIT_FIRE/BIT_WATER)) & ~((bitmap & BIT_WATER) * (BIT_WATER/BIT_FIRE))
as long as BIT_FIRE and BIT_WATER are single bits (powers of 2). You probably also want bitmap to be unsigned to insure that the compiler can easily optimize this down to a single shift, two bitwise ands, and a complement.
Of course, a good compiler would optimize your original code down to the same 4 instructions with no branch.
edit
Of course, I realized the above is incorrect -- only works if BIT_FIRE > BIT_WATER.
So just stick with the original if and let the compiler optimize it...
Promoting my comment to an answer. Note, it uses multiplication, but maybe it will be still useful to you (code on ideone.com):
#include <iostream>
int main()
{
int long unsigned bitmap_with_water = 0xF300003F;
int long unsigned bitmap_without_water = 0xF300000F;
int long unsigned bit_fire = 0x03000000;
int long unsigned bit_water = 0x00000030;
bitmap_with_water &= ~(bit_fire * static_cast<bool>(bitmap_with_water & bit_water));
bitmap_without_water &= ~(bit_fire * static_cast<bool>(bitmap_without_water & bit_water));
std::cout << (void*)(bitmap_with_water) << "\t" << (void*)(bitmap_without_water) << std::endl;
return (0);
}
Program output:
0xf000003f 0xf300000f
If you need to write a general purpose clear_if_set(int test, int clear, int bitmap) then this answer is useless.
If this is a specialized function and you know the shift distance from fire to water:
int water = bitmap & BIT_WATER;
int shifted = water << WATER_TO_FIRE_LSHIFT; // for example
bitmap &= ~shifted;
One-liner:
bitmap &= ~((bitmap & BIT_WATER) << WATER_TO_FIRE_LSHIFT);
If using bit numbers instead of pre-shifted bit masks is acceptable:
bitmap &= ~(((bitmap >> SHIFT_WATER) & 1) << SHIFT_FIRE)
Assuming BIT_WATER and BIT_FIRE are not the same bit then
the truth table for
if(bitmap & BIT_WATER) bitmap &= ~BIT_FIRE
is (BIT_WATER, old BIT_FIRE, new BIT_FIRE)
0 0 0
0 1 1
1 0 0
1 1 0
So from a bit perspective that is
BIT_FIRE = (~BIT_WATER)&BIT_FIRE;
1 0 0
1 1 1
0 0 0
0 1 0
Since I dont know the gap between your two bits then something like this which is excessive.
newbit = ((~(bitmap>>BIT_WATER_BIT))&(bitmap>>BIT_FIRE_BIT))&1;
bitmap&=~BIT_FIRE;
bitmap|=newbit<<BIT_FIRE_BIT;
Assuming I didnt make a typo...Also which I assume can be simplified if you take advantage of the specific bit numbers and not do something generic (shift BIT_WATER bit over to land on BIT_FIRE rather than shift everything right then left again. May not make it simpler though.
if bit water bit is 7 and bit fire bit is 3
bitmap = (((~(bitmap>>4))>>4)&(1<<3))&bitmap;
Or maybe this
bitmap = (((bitmap&(~BIT_WATER))^BIT_WATER)>>4)&bitmap;
where >>4 is the direction and delta between BIT_WATER and BIT_FIRE. fill in the proper delta.

Set individual bit in C++

I have a 5 byte data element and I need some help in figuring out how in C++ to set an individual bit of one of these byte; Please see my sample code below:
char m_TxBuf[4];
I would like to set bit 2 to high of byte m_TxBuf[1].
00000 0 00
^ This one
Any support is greatly appreciated;
Thanks!
Bitwise operators in C++.
"...set bit 2..."
Bit endianness.
I would like to set bit 2 to high of byte m_TxBuf[1];
m_TxBuf[1] |= 1 << 2
You can use bitwise-or (|) to set individual bits, and bitwise-and (&) to clear them.
int bitPos = 2; // bit position to set
m_TxBuf[1] |= (1 << bitPos);
m_TxBuf[1] |= 4;
To set a bit, you use bitwise or. The above uses compound assignment, which means the left side is one of the inputs and the output.
Typically we set bits using bitwise operator OR (operator| or operator|= as a shorthand).
Assuming 8-bits to a byte (where the MSB is considered the '7st' bit and the LSB considered the 0th: MSB 0) for simplicity:
char some_char = 0;
some_char |= 1 << 0; // set the 7th bit (least significant bit)
some_char |= 1 << 1; // set the 6th bit
some_char |= 1 << 2; // set the 5th bit
// etc.
We can write a simple function:
void set_bit(char& ch, unsigned int pos)
{
ch |= 1 << pos;
}
We can likewise test bits using operator&.
// If the 5th bit is set...
if (some_char & 1 << 2)
...
You should also consider std::bitset for this purpose which will make your life easier.
Just use std::bitset<40> and then index bits directly.