Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
May 1st, 2013, 12:20 PM
 maanasa
Registered User

Join Date: May 2013
Posts: 1
Time spent in forums: 7 m 25 sec
Reputation Power: 0
Bitwise operators

Dear DevShed,

How to shift a complete array using bit wise operators(<< or >>)?

For example: array[]=1<<i; is it possible??????

#2
May 1st, 2013, 12:47 PM
 dwise1_aol
Contributing User

Join Date: Jan 2003
Location: USA
Posts: 6,842
Time spent in forums: 3 Months 23 h 39 m 57 sec
Reputation Power: 2199
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:
Quote:
 ANSI/ISO 9899-1990 6.3.7 Bitwise shift operators . . . The result of E1 >> E2 is E1 right-shifted E2 bit positions. ... If E1 has a signed type and a negative value, the resulting value is implementation-defined.

Yet another detail that you will need to specify.

Last edited by dwise1_aol : May 1st, 2013 at 01:17 PM.

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Bitwise operators