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.
Related
Assuming x is a 8bit unsigned integer, what is the most efficient command to set the last two bits to 01 ?
So regardless of the initial value it should be x = ******01 in the final state.
In order to set
the last bit to 1, one can use OR like x |= 00000001, and
the forelast bit to 0, one can use AND like x &= 11111101 which is ~(1<<1).
Is there an arithmetic / logical operation that can be use to apply both operations at the same time?
Can this be answered independently of programm-specific implementation but pure logical operations?
Of course you can put both operation in one instructions.
x = (x & 0b11111100) | 1;
That at least saves one assignment and one memory read/write. However, most likely the compilers may optimize this anyway, even if put into two instructions.
Depending on the target CPU, compilers may even optimize the code into bit manipulation instructions that directly can set or reset single bits. And if the variable is locally heavily used, then most likely its kept in register.
So at the end the generated code may look at as simple as (pseudo asm):
load x
setBit 0
clearBit 1
store x
however it also may be compiled into something like
load x to R1
load immediate 0b11111100 to R2
and R1, R2
load immediate 1 to R2
or R1, R2
store R1 to x
For playing with things like this you may throw a look at compiler explorer https://godbolt.org/z/sMhG3YTx9
Please try removing the -O2 compiler option and see the difference between optimized and non-optimized code. Also you may try to switch to different cpu architectures and compilers
This is not possible with a dyadic bitwise operator. Because the second operand should allow to distinguish between "reset to 0", "set to 1" or "leave unchanged". This cannot be encoded in a single binary mask.
Instead, you can use the bitwise ternary operator and form the expression
x = 0b11111100 ??? x : 0b00000001.
Anyway, a piece of caution: this operator does not exist.
I came across the following declaration while working on a sample code in C++. Can anyone explain the use "|" while making the declaration?
static const DWORD c_FaceFrameFeatures = FaceFrameFeatures::FaceFrameFeatures_BoundingBoxInColorSpace
| FaceFrameFeatures::FaceFrameFeatures_PointsInColorSpace
| FaceFrameFeatures::FaceFrameFeatures_RotationOrientation
| FaceFrameFeatures::FaceFrameFeatures_Happy;
Note that DWORD is an alias for unsigned int.
This snippet is taken from the FaceBasicsD2D sample for Kinect V2.
What you have there is the creation of a "bitmask" using several const "enum" values combined using "bitwise OR" (the | character).
Typically this is done when several "flags" are desired in a compact, somewhat extensible representation. Only somewhat extensible because a DWORD is 32 bits so holds at most 32 flags.
Given that the flags usually have values which are all-bits-zero except one bit, you can also simply add them, though this is less conventional:
static const DWORD c_FaceFrameFeatures = FaceFrameFeatures::FaceFrameFeatures_BoundingBoxInColorSpace
+ FaceFrameFeatures::FaceFrameFeatures_PointsInColorSpace
+ FaceFrameFeatures::FaceFrameFeatures_RotationOrientation
+ FaceFrameFeatures::FaceFrameFeatures_Happy;
In short: The bitwise OR operator is setting multiple flags at once.
c_faceFrameFeatures is an unsigned int, and each bit of that int is used individually as a flag. So one bit will define whether the option PointsInColorSpace is true or false, and another bit will define RotationOrientation, and so on. So the intent of this code snippet is to set several flags at once during the declaration.
You could look at the documentation's list of FaceFrameFeatures flags, and note how each flag is defined as a single bit in hex notation.
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))
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)
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.