user2737926
user2737926

Reputation: 97

ERROR in understanding bit-wise operations

I have unsigned int (32bits) and want to divided into group of 3 short of 12 bits each. However, I unable to extract the numbers correctly. e.g. Let's say I have 32 bit unsigned int as follows :

1111 0000 1011 0000 1010 1001 1100 1101  

then I want something like this :

S1 = 1111 0000 1011 
s2 = 0000 1010 1001 
s3 = 1100 1101 

Program :

    #include<stdio.h>

    int main() {
            short s1,s2,s3 = 0
            unsigned int addr = 4194624;

            s1 = addr>>12;
            addr = addr>>12;
            printf("%d\n", s1);
            s2 = addr>>12;
            addr = addr>>12;
            printf("%d\n", s2);
            s3 = addr>>12;
            addr = addr>>12;
            printf("%d\n", s3);

            return 0;
    }

Upvotes: 1

Views: 129

Answers (3)

Rishabh Sharma
Rishabh Sharma

Reputation: 11

Copied from comments - see you have a 32 bit number first what i did was i store that in another variable and then right shifted it by 20 bits so the new number with me is a 12 bit number and then the same operation of getting the desired number was done on the other two 12 bit chains

#includde<stdio.h>
#include<conio.h>

void main()
{
    unsigned long a=4194624,e;
    int b,c,d;
    e=a;
    e=e>>20;
    b=e;
    e=a;
    e=e<<12;
    e=e>>20;
    c=e;
    e=a;
    e=e<<24;
    e=e>>24;
    d=e;
    printf(" %d %d %d ",b,c,d);
    getch(); 
}

Upvotes: 1

R Sahu
R Sahu

Reputation: 206567

This works for me.

// Just pick up the last 8 bits of addr and
// assign it to s3.
s3 = addr & 0xFF;

// Shift addr by 8 bits to the right, then pick up
// just the last 12 bits of the resulting number, and then
// assign it to s2.
s2 = (addr >> 8) & 0xFFF;

// Shift addr by 20 bits to the right and then assign
// the resulting number to s1.
s1 = (addr >> 20);

Upvotes: 2

4pie0
4pie0

Reputation: 29724

You can use such a function to extract bits:

short f( unsigned int number, int start, int end)
{
    unsigned int mask = (1 << (end - start)) - 1;
    return ( number >> start) & mask;
}

Then:

int main() {

    short s1,s2,s3 = 0;
    unsigned int addr = 4194624;

    s1 = f( addr, 20, 31);
    s2 = f( addr, 8, 19);
    s3 = f( addr, 0, 7);

    printf("%d\n", s1);
    printf("%d\n", s2);
    printf("%d\n", s3);
    return 0;
}

prints:

4

1

64

http://ideone.com/Q5mV94

Upvotes: 2

Related Questions