Anis_Stack
Anis_Stack

Reputation: 3452

bitwise operation to set decimal variable

I wrote a light program using bitwise operation.

#include <stdio.h>
int main ()
{
    int pos;
    unsigned int aaregister = 0;
    unsigned int result = 1;
    aaregister = aaregister|(1 << 0);
    printf("|0: %02X \n", aaregister);
    aaregister = aaregister | 1 << 1;
    printf("|1: %02X \n", aaregister);
    aaregister = aaregister | 0 << 2;
    printf("|2: %02X \n", aaregister);
    aaregister = aaregister | 1 << 3;
    printf("|3: %02X \n", aaregister);
    for (pos = 3; pos>=0;pos--) 
    {
         result = result & (aaregister & (1 >> pos));
        printf(" %d \n", result);
         printf("res : %02X \n", result);
    }
  return 0;
} 

my purpose is set aaregister to binary value 1011 and then set the result according to bit position.

if bit pos = 3 1 so result = 1

if pos = 2 0 so result = 0

if pos = 1 1 so result = 1

if pos = 0 1 so result = 1

but the program doesn't return that !!

what wrong with the c program ?

Upvotes: 1

Views: 114

Answers (3)

Arul
Arul

Reputation: 13

to set a bit you can use this logic

a=(1<<(pos-1))|a; 

Upvotes: -1

Tom Karzes
Tom Karzes

Reputation: 24100

New answer, based on what I believe the expected output is intended to be:

#include <stdio.h>

int main ()
{
    int pos;
    unsigned int aaregister = 0;
    unsigned int result = 0;
    aaregister |= 1 << 0;
    printf("|0: %02X \n", aaregister);
    aaregister |= 1 << 1;
    printf("|1: %02X \n", aaregister);
    aaregister |= 0 << 2;
    printf("|2: %02X \n", aaregister);
    aaregister |= 1 << 3;
    printf("|3: %02X \n", aaregister);
    for (pos = 3; pos>=0;pos--)
    {
        result = (aaregister >> pos) & 1;
        printf("Pos %d: res : %d\n", pos, result);
    }
    return 0;
}

The output is:

|0: 01
|1: 03
|2: 03
|3: 0B
Pos 3: res : 1
Pos 2: res : 0
Pos 1: res : 1
Pos 0: res : 1

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727017

You are shifting the wrong part: instead of shifting 1 to the right (which will produce zero when pos is not zero) you should shift aaregister to the right, like this:

result = result & ((aaregister >> pos) & 1);

In addition, the declaration of result needs to move inside the loop, so that you reset it back to 1 on each iteration (demo).

Now that your program is working, here are some important points about bit operations:

You cannot force a zero into a number by OR-ing - hence, aaregister | 0 << 1 operation is pointless. In order to force a zero you need to AND with an inverse, like this:

aaregister = aaregister & ~(1 << 1);

or better

aaregister &= ~(1 << 1);

Compound assignments make your code easier to read - instead of writing

aaregister = aaregister | 1 << 3;

write

aaregister |= (1 << 3);

Testing a bit can be done in any position - if you would like to check that position pos is set or not, use

if (aaregister & (1 << pos)) {
    ...
}

Upvotes: 3

Related Questions