Check if certain bits are set in a DWORD - c++

My question: I'm looking at the Characteristics member of the IMAGE_SECTION_HEADER struct. I want to know if a certain section is executable or not. How would I go about checking this? The Characteristics member is a DWORD, and I want to be able to know if it contains the value IMAGE_SCN_MEM_EXECUTE (0x20000000). What would the calculation for this look like? I'm guessing I have to use the modulo operator, but have no idea how.

if (imageSectionHeader.Characteristics & IMAGE_SCN_MEM_EXECUTE)
{
// Do work here...
}
This is called masking. You're masking the Characteristics value with IMAGE_SCN_MEM_EXECUTE mask to see if those specific bits are set. The condition above will only be true if all the bits set in the IMAGE_SCN_MEM_EXECUTE mask are also set in the Characteristics value.

It looks like IMAGE_SECTION_HEADER::Characteristics is a bit field. You want to check if the bit denoted by IMAGE_SCN_MEM_EXECUTE is set. To do that, you do the bitwise AND between Characteristics and IMAGE_SCN_MEM_EXECUTE:
header.Characteristics & IMAGE_SCN_MEM_EXECUTE
When converted to bool, this expression will be true only if the IMAGE_SCN_MEM_EXECUTE bit is set.

Found some facts about windows flag design :
Lets assume Flag A is "0x0001000", B is "0x0002000" and C is "0x0003000".
Characteristics may contain multibyte flag. Suppose exe contains flag A & B.
Then Characteristics value will be "0x0003000".
if we are checking (Characteristics&(A|B)) this will be okay but (Characteristics&(C)) will also return true.
But Microsoft designed flags in such way that no multiple flags having possibility to come together and form third flag.
If we check possible values of Characteristics closly, there are some intermediate values which are skipped to avoid above issue.
Bitwise AND(&) will always work for flag checking.
For Safety one can also write expression as follows:
if we wants to check for Flag1 & Flag2 in Characteristics.
((Characteristics & (Flag1|Flag2|Highest Bit flag in flag list)==(Flag1|Flag2))

Related

Why compare a flag with the result of bitwise AND of a bitmask and the flag?

As a follow-up to "How to use bitmask": When I want to test if a certain flag is set in a given bitmask, I would usually do so solely through the usage of a bitwise AND:
if(bitmask & flag) { …
Yet I frequently see something like this:
if((bitmask & flag) == flag) { …
This is something I observed on both, strongly and weakly typed languages, which is ruling out some sort of prevention for type-casting disasters. The only scenario I can come up with in which the two tests were not equivalent were if flag happens to have actually more than one bit set and all of those are required to be set in bitmask for the condition to pass. Is that all or am I missing something here?
Bonus: Do compilers have means to recognize a flag that will have at most one bit set during runtime and optimize the (possibly bogus) comparison away?
As you point out, the two conditions aren't equivalent. The check (bitmask & flag)1 is checking if any bit set in flag is set in bitmask, while the (bitmask & flag) == flag check checks if all bits in flag are set.
In cases where there will only ever be one bit set, you might also see the second form rather than the first in languages like Java that don't have an implicit conversion from integral types to boolean. The exact equivalent of the first check in those languages is (bitmask & flag) != 0 and that form is probably also more canonical even for checking a single flag.
In terms of actual generated code it's mostly all academic.
For known-at-compile-time2 flags where the compiler can see that the flag only has one bit, both forms will generally be compiled to identical code - see the fixedA and fixedB functions in that link.
For functions with unknown flags, the forms aren't equivalent, as mentioned, so the code is different (see the unknownA and B functions) but the performance difference is very minor.
1 Or, equivalently, (bitmask & flag) != 0 in languages that don't have an implicit conversion from integer types to boolean.
2 Importantly, this includes functions that accept variable flags but where the caller is using a constant flag and the function is inlined.

How to query if any bit in a range is set in a C++ std::bitset?

I am looking for a C++ bitset implementation that can answer if a bit is set in a range. std::bitset, vector, and boost::dynamic_bitset all give access to individual bits that I can loop over, but that isn't the most efficient way to query a range of bits to ask if any bit is set- I don't even need to know which one.
bitset b;
if(b.any(33, 199))
{
// ...
}
Is there a library that provides this? I would like to run some benchmarks against other implementations (including one I may have to write), but I can't find any that appear to implement this functionality.
Unfortunately in C++11 bitset it is not possible to set a range of bits to the given value by just specifying the boundaries of the range. Iterating over individual bits seems the most we can do. It is also not possible to check if all bits inside the range are set to the same value (1,0).
There is an open source project in Git that provides an alternative implementation of the BitSet (RangedBitset) that supports these operations. It uses an array of uint_64t_ words of any size internally, but can also handle ranges specified with the accuracy of the single bit. There you can do the things like
a.set(4, 8, true); // set the range [ 4 .. 8 [ to true
bool is_all_range = a.check(2, 6, true); // check if all range is set to 1.
To check if some bit is set in the range [x,y] in bitset, you can use bs._Find_next(x-1). It returns the next set bit after the position x-1.
Then you can check if the returned value is <=y or not.
bool Find_if_bitset_has_any_set_bit_in_range(bitset<M> &bs, int x, int y){
if(bs._Find_next(x-1)<=y) return 1; //TRUE
return 0; //FALSE
}
C++11's bitset provides the any() method that you are after, but if that isn't an option then just use b.to_ulong() and check for non zero.

C++ SDL What does the | do?

screen = SDL_SetVideoMode(1000,1000,32, SDL_HWSURFACE | SDL_FULLSCREEN);
What does the | do in SDL_HWSURFACE | SDL_FULLSCREEN? (I tried googling this but google wont accept special characters..)
C / C++ APIs often set up bit 'flags' when there are a lot of different, non-mutually exclusive options that can be set for a given function call. Each of the flags will be assigned a bit position in a value (often a DWORD or other large integer type). One or more of these bits can then be set by bitwise OR-ing a collection of defined constants that represent the options and give you a more clear label to identify them than a raw numeric constant. The resultant value is passed as a single argument to the API function, which helps to keep the signature manageable.
In this particular case, SDL_HWSURFACE and SDL_FULLSCREEN represent options that can be passed in to the SDL_SetVideoMode call. There are probably several other possible options available as well that were not set in this case. This particular call sets the two options by bitwise OR-ing the flag constants together, and passing the result as the last parameter.
That's the bitwise OR operator. It applies it to SDL_HWSURFACE and SDL_FULLSCREEN.
The other answers have explained it's a bitwise OR, but you probably want to know how that works:
The flags are passed as a binary number, like 00001000 or 01000000, and each bit represents an individual flag. So the first bit (0) means HW_SURFACE is off, and the second bit (1) means FULLSCREEN is on. (Note that these are examples, I'm not sure about the actual bits.)
So what the bitwise OR function does is combine those two flags by comparing each bit and saying "Is this bit OR this bit 1?" and if either is 1, it will set the result to 1. This will provide the result 01001000 which can be parsed by SDL to set the appropriate flags.
The | operator means bitwise or. That means each bit in the result is set if the corresponding bit in the left hand or the right hand value is set. So 1 | 2 = 3, because 1 in binary is 01 and 2 in binary is 10. So the result in binary is 11 which is 3 in decimal.
In your example this is used to pass a lot of different on/off options to a function. Each of the constants has exactly one bit set. The function then looks at the value you pass and using the bitwise and operator & to check which ones you specified.

Use logical OR || to combine two integers?

In this MSDN article on file sharing mode with std::ofstream, Microsoft writes:
To combine the filebuf::sh_read and filebuf::sh_write modes, use the logical OR (||) operator.
Both constants are of type int, as far as I can see, so I don't understand why we should use the logical OR instead of the bitwise OR (|). I always thought that the logical OR produces a Boolean value, so there is no way of interpreting the result?
It is a documentation error. In later versions, they have restructured the documentation, delegating the explanation of bitmask types to the following page:
A bitmask type can be implemented as either an integer type or an enumeration. In either case, you can perform bitwise operations (such as AND and OR) on values of the same bitmask type. The elements A and B of a bitmask type are nonzero values such that A & B is zero.
Get there via
google
http://msdn.microsoft.com/en-us/library/5785s5ts(v=vs.71).aspx
http://msdn.microsoft.com/en-us/library/7z434859(v=vs.71).aspx
http://msdn.microsoft.com/en-us/library/t60aakye(v=VS.71).aspx
http://msdn.microsoft.com/en-us/library/y1et11xw(v=VS.71).aspx
http://msdn.microsoft.com/en-us/library/5kb732k7(v=VS.71).aspx
Yay! for MSDN navigation. Also, VS2010 documentation has been altered again: the newest page doesn't even describe the semantics of the flags fields anymore (allthough, you could take one mention of _Mode | ios_base::out to imply that the params are bitmask combinations)

How do you use bitwise flags in C++?

As per this website, I wish to represent a Maze with a 2 dimensional array of 16 bit integers.
Each 16 bit integer needs to hold the following information:
Here's one way to do it (this is by no means the only way): a 12x16 maze grid can be represented as an array m[16][12] of 16-bit integers. Each array element would contains all the information for a single corresponding cell in the grid, with the integer bits mapped like this:
(source: mazeworks.com)
To knock down a wall, set a border, or create a particular path, all we need to do is flip bits in one or two array elements.
How do I use bitwise flags on 16 bit integers so I can set each one of those bits and check if they are set.
I'd like to do it in an easily readable way (ie, Border.W, Border.E, Walls.N, etc).
How is this generally done in C++? Do I use hexidecimal to represent each one (ie, Walls.N = 0x02, Walls.E = 0x04, etc)? Should I use an enum?
See also How do you set, clear, and toggle a single bit?.
If you want to use bitfields then this is an easy way:
typedef struct MAZENODE
{
bool backtrack_north:1;
bool backtrack_south:1;
bool backtrack_east:1;
bool backtrack_west:1;
bool solution_north:1;
bool solution_south:1;
bool solution_east:1;
bool solution_west:1;
bool maze_north:1;
bool maze_south:1;
bool maze_east:1;
bool maze_west:1;
bool walls_north:1;
bool walls_south:1;
bool walls_east:1;
bool walls_west:1;
};
Then your code can just test each one for true or false.
Use std::bitset
Use hex constants/enums and bitwise operations if you care about which particular bits mean what.
Otherwise, use C++ bitfields (but be aware that the ordering of bits in the integer will be compiler-dependent).
Learn your bitwise opertors: &, |, ^, and !.
At the top of a lot of C/C++ files I have seen flags defined in hex to mask each bit.
#define ONE 0x0001
To see if a bit is turned on, you AND it with 1. To turn it on, you OR it with 1. To toggle like a switch, XOR it with 1.
To manipulate sets of bits, you can also use ....
std::bitset<N>
std::bitset<4*4> bits;
bits[ 10 ] = false;
bits.set(10);
bits.flip();
assert( !bits.test(10) );
You can do it with hexadecimal flags or enums as you suggested, but the most readable/self-documenting is probably to use what are called "bitfields" (for details, Google for C++ bitfields).
Yes a good way is to use hex decimal to represent the bit patterns. Then you use the bitwise operators to manipulate your 16-bit ints.
For example:
if(x & 0x01){} // tests if bit 0 is set using bitwise AND
x ^= 0x02; // toggles bit 1 (0 based) using bitwise XOR
x |= 0x10; // sets bit 4 (0 based) using bitwise OR
I'm not a huge fan of bitset. It's just more typing in my opinion. And it doesn't hide what you are doing anyway. You still have to & && | bits. Unless you are picking on just 1 bit. That may work for small groups of flags. Not that we need to hide what we are doing either. But the intention of a class is usually to make something easier for it's users. I don't think this class accomplishes it.
Say for instance, you have a flag system with .. 64 flags. If you want to test.. I don't know.. 39 of them in 1 if statement to see if they are all on... using bitfields is a huge pain. You have to type them all out.. Course. I'm making the assumption you use only bitfields functionality and not mix and match methods. Same thing with bitset. Unless I am missing something with the class.. which is quite possible since I rarely use it.. I don't see a way you can test all 39 flags unless you type out the hole thing or resort to "standard methods" (using enum flag lists or some defined value for 39 bits and using the bitsets && operator). This can start to get messy depending on your approach. And I know.. 64 flags sounds like a lot. And well. It is.. depending on what you are doing. Personally speaking, most of the projects I'm involved with depend on flag systems. So actually.. 64 is not that unheard of. Though 16~32 is far more common in my experience. I'm actually helping out in a project right now where one flag system has 640 bits. It's basically a privilege system. So it makes some sense to arrange them all together... However.. admittedly.. I would like to break that up a bit.. but.. eh... I'm helping.. not creating.