Bitwise setting in C++ - c++

enum AccessSource
{
AccessSourceNull = 0x00000001,
AccessSourceSec = 0x00000002,
AccessSourceIpo = 0x00000004,
AccessSourceSSA = 0x00000008,
AccessSourceUpgrade = 0x00000010,
AccessSourceDelta = 0x00000020,
AccessSourcePhoneM = 0x00000040,
AccessSourceSoft = 0x00000080,
AccessSourceCR = 0x00000100,
AccessSourceA = 0x00000200,
AccessSourceE = 0x00000400,
AccessSourceAll = 0xFFFFFFFF
};
What is the value of AccessSourceAll ?? is it -1? or is it maximum value?
I have a parameter ULONG x , whose default value is AccessSourceAll(that means access to all). How do i remove the access right of AccessSourceE only?
How to add the access right of AccessSourceE again?
If i have a particular value in x, then how do i know whether AccessSourceE is set or not?

The value of AccessSourceAll is (int)0xFFFFFFFF since enum is of type int in C.
The unset just AccessSourceE use:
x & ~AccessSourceE // to assign: x &= ~AccessSourceE;
To add, use
x | AccessSourceE // to assign: x |= AccessSourceE;
To test,
if (x & AccessSourceE) { ... }

I'm not sure it'll actually matter since it is a mask which will clearly have a bit set for each of the other values.
If you are assigning it to a ULONG, it will be an unsigned type. To set/remove values use bitwise logic:
x |= AccessSourceE; /* set SourceE */
x &= ~AccessSourceE; /* unset SourceE */
if(x & AccessSourceE) /* test SourceE */

You can use the ^ operator for this.
For Example :
unsigned long l_unValue = AccessSource::AccessSourceAll;
l_unValue = l_unValue ^ AccessSource::AccessSourceE;
The above statement will remove "AccessSourceE" from "AccessSourceAll".

Related

qt QFlags: signed value is out of range for enum constant

I got following warnings for the enum value xxxxx920P4 building a qt C++ project. And I found out in the debugging that xxxxx920P4 is now equals to xxxxxundefine (0x00000000), which causes the unexpected result. How should I resolve this problem?
I'm using Qt version: 4.8.7 and Visual studio 2010.
The following loop will not be executed. gVersions[0].verNum is "xxxxx920P4", so I guess "xxxxx920P4"'s value has been truncated and now it equals to 0x00000000.
for(int i=0; gVersions[i].verNum != xxxxxundefine ; i++)
{
}
Doc for Qt Qflags class: https://doc.qt.io/qt-5/qflags.html
warning C4341: 'xxxxx920P4' : signed value is out of range for enum constant
warning C4309: 'initializing' : truncation of constant value
enum Version
{
xxxxxundefine = 0x00000000,
xxxxx400 = 0x00000001,
xxxxx401 = 0x00000002,
xxxxx410 = 0x00000004,
xxxxx411 = 0x00000008,
xxxxx412 = 0x00000010,
xxxxx420 = 0x00000020,
xxxxx430 = 0x00000040,
xxxxx431 = 0x00000080,
xxxxx432 = 0x00000100,
xxxxx440 = 0x00000200,
xxxxx500 = 0x00000400,
xxxxx510 = 0x00000800,
xxxxx520 = 0x00001000,
xxxxx521 = 0x00002000,
xxxxx600 = 0x00004000,
xxxxx611 = 0x00008000,
xxxxx620 = 0x00010000,
xxxxx621 = 0x00020000,
xxxxx700 = 0x00040000,
xxxxx910 = 0x00080000,
xxxxx910P5 = 0x00100000,
xxxxx910P6 = 0x00200000,
xxxxx910P11 = 0x00400000,
xxxxx910P12 = 0x00800000,
xxxxx910P13 = 0x01000000,
xxxxx910P14 = 0x02000000,
xxxxx910P15 = 0x04000000,
xxxxx910P16 = 0x08000000,
xxxxx920 = 0x10000000,
xxxxx920P1 = 0x20000000,
xxxxx920P2 = 0x40000000,
xxxxx920P3 = 0x80000000,
xxxxx920P4 = 0x100000000,
}; Q_DECLARE_FLAGS(Versions, Version)
The last value is too long to fit into a a non-long int. While newer compilers may try to choose a larger integral type for it, some older ones would complain. GCC tends to do the former unless you choose type explicitly. Note that second to last value 0x80000000 or any combination of masks involving it would not fit into int, it's essentially a negative -2147483648.
enum Version : long long
{
//...
xxxxx920P4 = 0x100000000,
};
PS. Apparently Qt5 doesn't support something different from (unsigned)int: https://doc.qt.io/qt-5/qflags.html

Check Multiple boolean condition using dword in c++

I am really new to using DWORD in C++ in place of boolean. Hence, please excuse my question.
I have an enum:
enum foo
{
foo1 = 0x0;
foo2 = 0x1
//....
}
DWORD foo;
I am using this enum to check for multiple conditions:
if(somethinghappenstothisvariable)
{
foo|= foo1;
}
if(somethinghappenstosecondvariable)
{
foo|=foo2;
}
Now in another file I have to check for individual variables condition
if(foo &foo1)
{
//do something;
}
if(foo & foo2)
{
//do something;
}
I figured that |= adds up the value to the DWORD if both conditions are true which leads to foo & foo2 only to be true while foo & foo1 will not be as the value of DWORD will be 1. Hence, I was wondering if there is anyway I can check this for individual DWORD value.
The issue: 1 = bit 0, 0 is invalid.
To the check each "condition" should represent a separate bit (bit 0 = 1, bit 1 = 2, etc.)
So - a simple change: foo1 = 0x01; foo2 = 0x02; should fix it.
NOTE: any additional checks should represent bit values, NOT ordinal.
In other words, foo3 = 0x04; (not 0x03;)
You can make it correct easier by creating these constants with shifts:
enum foo
{
foo1 = 1 << 0;
foo2 = 1 << 1;
foo3 = 1 << 2;
//....
}
This way you can be sure that each mask has a single bit set.

Bit Field struct list

I have the following bitfield struct:
struct DescriptorByte
{
unsigned short IsImmedCalc : 1;
unsigned short IsPrefix : 1;
unsigned short NoMemOp : 1;
unsigned short Size : 5;
};
I want to create an table for holding many DescriptorByte struct, so i created this:
struct OpcodeList
{
DescriptorByte ADD_8_MO;
DescriptorByte ADD_32_MO;
DescriptorByte ADD_8_OM;
DescriptorByte ADD_32_OM;
DescriptorByte ADD_8_OI = { TRUE, FALSE, TRUE, 1 + 1 };
DescriptorByte ADD_32_OI = { TRUE, FALSE, TRUE, 1 + 4 };
DescriptorByte PUSH_ES = { TRUE, FALSE, TRUE, 1 };
};
So is this the same as having an struct with each member beign 1 byte long?. Also i want to be able to reference the initializator member like this:
DescriptorByte ADD_8_OI = { IsImmedCalc = true, Size = 1 };
but visual studio is not letting me. The idea behind all of this is having a table of DescriptorByte, is this the best approach? also what is the best initialization method? thanks.
"is this the same as having a struct with each member being 1 byte long?"
Your compiler might add padding if you do not use #pragma pack or something similar.
But there isn't any padding required in this specific case, so essentially the answer is yes.
Just change the unsigned short to unsigned char and each member will be 1 byte long.
Add '.' on the left side of each field:
DescriptorByte ADD_8_OI = { .IsImmedCalc = true, .Size = 1 };
Alternatively, just write the actual values in the correct order (missing ones will be set to 0):
DescriptorByte ADD_8_OI = { true, 1 };
EDIT: Posted this thinking it was a C# question, sorry! Leaving it here for others.
C# does not support bit-fields. However, you can still 'emulate' that behavior using a single member variable of the appropriate size along with various getter properties.
In your example, you want to use an unsigned 8-bit integer value (byte) and encapsulate those bitfields. Have no fear, you can still use a struct to do all this to make marshaling and interop easier.
So let's take your DescriptorByte and recreate what you are looking to do:
struct DescriptorByte
{
static readonly byte IsImmedCalcFlag = 0x80; // 1000 0000
static readonly byte IsPrefixFlag = 0x40; // 0100 0000
static readonly byte NoMemOpFlag = 0x20; // 0010 0000
static readonly byte FlagsBitMask = 0xE0; // 1110 0000
static readonly byte SizeBitMask = 0x1F; // 0001 1111
byte field;
public bool IsImmedCalc
{
get { return (field & IsImmedCalcFlag) > 0; }
set
{
if (value)
field = (byte)(field | IsImmedCalcFlag); // Set the bit
else
field = (byte)(field & ~IsImmedCalcFlag); // Clear the bit
}
}
public bool IsPrefix
{
get { return (field & IsPrefixFlag) > 0; }
set
{
if (value)
field = (byte)(field | IsPrefixFlag); // Set the bit
else
field = (byte)(field & ~IsPrefixFlag); // Clear the bit
}
}
public bool NoMemOp
{
get { return (field & NoMemOpFlag) > 0; }
set
{
if (value)
field = (byte)(field | NoMemOpFlag); // Set the bit
else
field = (byte)(field & ~NoMemOpFlag); // Clear the bit
}
}
public byte Size
{
get { return (byte)(field & SizeBitMask); }
set { field = (byte)((field & FlagsBitMask) | (value & SizeBitMask)); }
}
}

Testing whether specific bits are set in a DWORD flag

I have a DWORD variable & I want to test if specific bits are set in it. I have my code below but I am not sure if I am transferring the bits from the win32 data type KBDLLHOOKSTRUCT to my lparam datatype correctly?
See MSDN that documents the DWORD flag variable: http://msdn.microsoft.com/en-us/library/ms644967(v=vs.85).aspx
union KeyState
{
LPARAM lparam;
struct
{
unsigned nRepeatCount : 16;
unsigned nScanCode : 8;
unsigned nExtended : 1;
unsigned nReserved : 4;
unsigned nContext : 1;
unsigned nPrev : 1;
unsigned nTrans : 1;
};
};
KBDLLHOOKSTRUCT keyInfo = *((KBDLLHOOKSTRUCT*)lParam);
KeyState myParam;
myParam.nRepeatCount = 1;
myParam.nScanCode = keyInfo.scanCode;
myParam.nExtended = keyInfo.flags && LLKHF_EXTENDED; // maybe it should be keyInfo.flags & LLKHF_EXTENDED or keyInfo.flags >> LLKHF_EXTENDED
myParam.nReserved = 0;
myParam.nContext = keyInfo.flags && LLKHF_ALTDOWN;
myParam.nPrev = 0; // can store the last key pressed as virtual key/code, then check against this one, if its the same then set this to 1 else do 0
myParam.nTrans = keyInfo.flags && LLKHF_UP;
// Or maybe I shd do this to transfer bits...
myParam.nRepeatCount = 1;
myParam.nScanCode = keyInfo.scanCode;
myParam.nExtended = keyInfo.flags & 0x01;
myParam.nReserved = (keyInfo.flags >> 0x01) & (1<<3)-1;
myParam.nContext = keyInfo.flags & 0x05;
myParam.nPrev = 0; // can store the last key pressed as virtual key/code, then check against this one, if its the same then set this to 1 else do 0
myParam.nTrans = keyInfo.flags & 0x07;
Rather than
myParam.nExtended = keyInfo.flags && LLKHF_EXTENDED
you need
myParam.nExtended = (keyInfo.flags & LLKHF_EXTENDED) != 0;
It's & not && because you want a bitwise and not a logical and. And the !=0 ensures the answer is either 0 or 1 (rather than 0 or some-other-nonzero-value) so it can be represented in your one-bit bitfield.
CheckBits(DWORD var, DWORD mask)
{
DWORD setbits=var&mask; //Find all bits are set
DWORD diffbits=setbits^mask; //Find all set bits that differ from mask
return diffbits!=0; //Retrun True if all specific bits in variable are set
}
If you want to merge two bits, you would use | (bitwise OR) operator:
myParam.nExtended = keyInfo.flags | LLKHF_EXTENDED;
myParam.nExtended = keyInfo.flags | 0x01;
To check if bit was set, you would use & (bitwise AND) operator:
if(myParam.nExtended & LLKHF_EXTENDED) ...

How to make functions with flag parameters? (C++)

How could I make a function with flags like how Windows' CreateWindow(...style | style,...), for example, a createnum function:
int CreateNum(flag flags) //???
{
int num = 0;
if(flags == GREATER_THAN_TEN)
num = 11;
if(flags == EVEN && ((num % 2) == 1)
num++;
else if(flags == ODD && ((num % 2) == 0)
num++;
return num;
}
//called like this
int Number = CreateNum(GREATER_THAN_TEN | EVEN);
Is this possible, and if so, how?
You can define an enum specifying "single bit" values (note that the enclosing struct is acting here only as a naming context, so that you can write e.g. MyFlags::EVEN):
struct MyFlags{
enum Value{
EVEN = 0x01,
ODD = 0x02,
ANOTHER_FLAG = 0x04,
YET_ANOTHER_FLAG = 0x08,
SOMETHING_ELSE = 0x10,
SOMETHING_COMPLETELY_DIFFERENT = 0x20
};
};
and then use it like this:
int CreateNum(MyFlags::Value flags){
if (flags & MyFlags::EVEN){
// do something...
}
}
void main(){
CreateNum((MyFlags::Value)(MyFlags::EVEN | MyFlags::ODD));
}
or simply like this:
int CreateNum(int flags){
if (flags & MyFlags::EVEN){
// do something...
}
}
void main(){
CreateNum(MyFlags::EVEN | MyFlags::ODD);
}
You could also simply declare integer constants, but the enum is clearer in my opinion.
Note: I updated the post to take some comments into account, thanks!
I upvoted orsogufo's answer, but I always liked doing the following for defining the values:
enum Value{
EVEN = (1<<0),
ODD = (1<<2),
ANOTHER_FLAG = (1<<3),
YET_ANOTHER_FLAG = (1<<4),
SOMETHING_ELSE = (1<<5),
SOMETHING_COMPLETELY_DIFFERENT = (1<<6),
ANOTHER_EVEN = EVEN|ANOTHER_FLAG
};
<< is the shift operator. Incrementing the right side lets you generate sequential bit masks by moving the 1 over, one bit at a time. This has the same values for the bare flags, but reads easier to my eyes and makes it obvious if you skip or duplicate a value.
I also like combining some common flag combinations when appropriate.
You can use const int like this:
const int FLAG1 = 0x0001;
const int FLAG2 = 0x0010;
const int FLAG3 = 0x0100;
// ...
And when you use it:
int CreateNum(int flags)
{
if( flags & FLAG1 )
// FLAG1 is present
if( flags & FLAG2 )
// FLAG2 is present
// ...
}
Of course you can put one or more flag in your flags using the | operator.
Use powers of two as the individual constants, like
enum Flags { EVEN = 0x1, ODD = 0x2, GREATER_TEN = 0x4 };
and you use the logical and operator '&' for testing, like
if( flags & GREATER_THAN_TEN)
num = 11;
if( (flags & EVEN) && (num % 2) == 1 )
num++;
else if ( (flags & ODD) && (num % 2) == 0 )
num++;
return num;
You've got your tests wrong. What you want is something like (flags & EVEN), where EVEN is an integer with a single bit set (1, 2, 4, 8, 16 - some power of 2). (The integer can be an int or an enum. You could have a macro, but that's generally not a good idea.)
You can use the notation you listed, by overloading flags::operator==(flagvalue f), but it's a bad idea.
enum flags {
EVEN = 0x0100,
ODD = 0x0200,
BELOW_TEN = 0x0400,
ABOVETEN = 0x0800,
HUNDRED = 0x1000,
MASK = 0xff00
};
void some_func(int id_and_flags)
{
int the_id = id_and_flags & ~MASK;
int flags = id_and_flags & MASK;
if ((flags & EVEN) && (the_id % 2) == 1)
++the_id;
if ((flags & ODD) && (the_id % 2) == 0)
++the_id;
// etc
}
Illustrates masking of bit fields too which can be useful when you just need to bolt on a simplistic bit of extra functionality without adding any extra data structure.