#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    1
    Rep 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. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    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:
    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 12:17 PM.

IMN logo majestic logo threadwatch logo seochat tools logo