C unsigned int array and bit shifts

Darrel picture Darrel · Nov 22, 2009 · Viewed 17.4k times · Source

If i have an array of short unsigned ints.

Would shifting array[k+1] left by 8 bits, put 8 bits into the lower half of array[k+1]?

Or do they simply drop off as they have gone outside of the allocated space for the element?

Answer

user181548 picture user181548 · Nov 22, 2009

They drop off. You can't affect the other bits this way. Try it:

#include <stdio.h>

void print_a (short * a)
{
    int i;
    for (i = 0; i < 3; i++)
        printf ("%d:%X\n", i, a[i]);
}

int main ()
{
    short a[3] = {1, -1, 3};
    print_a (a);
    a[1] <<= 8;
    print_a (a);
    return 0;
}

Output is

0:1
1:FFFFFFFF
2:3
0:1
1:FFFFFF00
2:3