YAKOVM
YAKOVM

Reputation: 10153

performing bit-wise AND with int and shifting

This question is based on: Shift with 64 bit int The origin of the question is - I define an enum ,which presents different masks. And need to make & of the variable with enum (mask) after that shift the result right. Since enum type is always int,the variable was defined also as int.But as you can see there is a problem shifting right negative numbers. what can be done to solve that?

Upvotes: 0

Views: 134

Answers (3)

James Kanze
James Kanze

Reputation: 154027

First, the enum type is not always int; in C++11, you can even force it to be an unsigned type. And second, even when the underlying type is int, you can (and should) freely cast to and from unsigned with no real risk. You can, for example, overload the operator& thusly:

MyEnum
operator&( MyEnum lhs, MyEnum rhs )
{
    return static_cast<MyEnum>(
        static_cast<unsigned>( lhs) & static_cast<unsigned>( rhs ) );
}

For extracting fields that may be in the middle somewhere:

int
getFieldX( MyEnum values )
{
    return static_cast<unsigned>(values & fieldXMask) >> fieldXOffset;
}

This will ensure correct behavior (and once the unsigned value has been shifted, it should convert to int without loss of value).

Upvotes: 4

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71009

I suggest you static cast the value of the enumeration to unsigned long long before shifting. I think this is the safest option you can use.

Upvotes: 1

sheu
sheu

Reputation: 5763

You could do the shift first, then AND against the shifted mask, to work around this.

Upvotes: 0

Related Questions