goodies
goodies

Reputation: 543

Reverse Value using Not Operator

I am just want to reverse the binary values of an integer using NOT ( ~ ) operator but when i were doing like this

struct rev
{
        unsigned i:3;  //for only 3 bits means 000 to 111
};
r.i = 5;

printf(" Reverse of %d  =  %u  \n",r.i,~(r.i));

it was giving me Reverse of 5 = 4294967290

but i want Reverse of 5 = 2 because i am using 3 bits so if i will do its NOT then 5 will be changed into 2 but it was not showing like this,it was giving me result as fffffffa i dont know why.

Means what i want is interchange 1 and 0 only thru NOT operator. i want

0   -   7
1   -   6
2   -   5

... like this.

Thanks.

Upvotes: 0

Views: 407

Answers (2)

Mats Petersson
Mats Petersson

Reputation: 129464

Although the stored value of i is 3 bits, when you use it for calculations in C or C++, it gets promoted to full size (32 bits, in this case).

You can solve it by :

rev r;
rev s;

r.i = 5;
s.i = ~r.i;

printf(" Reverse of %d  =  %u  \n",r.i,s.i);

Edit: You could write a class that provides a uint3:

class uint3
{
  private:
     unsigned val;
     enum { mask = 7; };
  public:
    uint3(unsigned int v = 0) { val = v & mask; }
    uint3 operator=(uint3 v) { val = v.val; return *this; }
    operator int() { return val; }
};

uint3 operator~(uint3 v) { return uint3(~(int)v); }

uint3 r = 5;
printf(" Reverse of %d  =  %u  \n",(int)r, (int(~r)));

I haven't compiled the above, but something along those lines.

Upvotes: 4

syam
syam

Reputation: 15089

operator~ reverses all the bits of your unsigned value (typically, a 32 bits integer).

To limit this to 3 bits you need a bitwise and operation in order to apply a bit mask:

~variable & 7

Upvotes: 1

Related Questions