Dear DevShed,
How to shift a complete array using bit wise operators(<< or >>)?
For example: array[]=1<<i; is it possible??????
Dear DevShed,
How to shift a complete array using bit wise operators(<< or >>)?
For example: array[]=1<<i; is it possible??????
In that way, no. Bit wise operators only work on a single integer-type value. In order to apply a shift operation to an all elements of an array, you would need to apply it to each element individually. That can easily be done with a for-loop that iterates through the array.
Now, what about the bits that shift out? Do you want them to shift into the neighboring element? Or do you just want to shift in zeros, which normally happens in a shift?
For example, let us assume a byte array (ie, unsigned char), ary, in which ary[0] is the most significant byte (MSB). Let us assume that it has four elements, so ary[3] would the the least significant byte (LSB). Thus bits shifting left out of one byte would then shift into the neighboring byte with a lower index number (eg, left shifting bits out of ary[2] into ary[1]), and bit shifting right out would shift into the neighbor with a higher index (eg, right shifting bits out of ary[2] into ary[3]).
Assigning arbitrary numbers to this example:
ary[0] = 0x42; // MSB
ary[1] = 0x91;
ary[2] = 0x44;
ary[3] = 0xA6; // LSB
If we left shift by four and shift bits into the preceding byte, we end up with:
ary[0] = 0x29; // MSB
ary[1] = 0x14;
ary[2] = 0x4A;
ary[3] = 0x60; // LSB
If we left shift by four and do not shift bits in, then we end up with:
ary[0] = 0x20; // MSB
ary[1] = 0x10;
ary[2] = 0x40;
ary[3] = 0x60; // LSB
Similarly, if we right shift and shift bits in:
ary[0] = 0x04; // MSB
ary[1] = 0x29;
ary[2] = 0x14;
ary[3] = 0x4A; // LSB
So then, just exactly what do you have in mind?
PS
Just double-checked something.
Generally in C, when you perform a shift, zeroes get shifted in; this is called a logical shift. However, sometimes when you right-shift a negative number (the most significant bit, which is the sign bit, is set to 1), then you perform an arithmetic shift in which 1's are shifted in. However, whether an arithmetic right shift happens is defined by the implementation and hence is not portable:
Yet another detail that you will need to specify.
Last edited by dwise1_aol; May 1st, 2013 at 01:17 PM.