Re: left shift count >= width of type

Discussion in 'C Programming' started by Thad Smith, Nov 3, 2011.

  1. Thad Smith

    Thad Smith Guest

    On 11/2/2011 3:55 AM, Alessandro Basili wrote:
    > Hi,
    > here's a simple program snippet that I'm dealing with and worried about
    > potential pitfalls:
    >
    > #define BITS_PER_UNIT 32
    > [...]
    > int foo, bar;
    >
    > bar = 0xAAAA5555;
    > foo = bar& ~ ((int) 1<< BITS_PER_UNIT);
    > [...]
    >
    > Strictly speaking the shift operations should report a warning (left
    > shift count>= width of type), since 1 is of type int (correct me if I'm
    > wrong).
    > Since this snippet is part of a very old implementation of g21k compiler
    > for ADSP21xxx, I'm wondering why do we need to shift at all, isn't the
    > above foo assignment equal to the following:
    >
    > foo = bar;


    Others have mentioned the undefined behavior if int is 32 bits.

    Let's assume that ints contain more than 33 bits to eliminate the undefined
    behavior. I'll assume that ints are 40 bits.

    The assignment to foo is equivalent to
    foo = bar & (int)0xfeffffffff;

    when the programmer probably intended

    foo = bar & 0x00ffffffff;

    To keep the lower BITS_PER_UNIT bits (at least one) I would have written

    foo = bar & (((1u << (BITS_PER_UNIT-1))-1)*2 +1);

    That should work, assuming the implementation has at least BITS_PER_UNIT bits in
    an unsigned int. If bar is an unsigned int, then replace 1u with 1ul.

    The embedded compiler I work with optimizes out anding with all one bits, so it
    would have no run-time penalty.


    Thad
     
    Thad Smith, Nov 3, 2011
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Wenjie
    Replies:
    3
    Views:
    1,092
    Ron Samuel Klatchko
    Jul 11, 2003
  2. Santosh Nayak

    Left Shift / Right Shift Operators

    Santosh Nayak, Nov 30, 2006, in forum: C Programming
    Replies:
    16
    Views:
    1,506
    CBFalconer
    Nov 30, 2006
  3. Sanny
    Replies:
    38
    Views:
    3,570
    Thomas Richter
    Apr 29, 2011
  4. pc
    Replies:
    2
    Views:
    1,391
    crisgoogle
    Jun 8, 2011
  5. James Kuyper

    Re: left shift count >= width of type

    James Kuyper, Nov 2, 2011, in forum: C Programming
    Replies:
    3
    Views:
    859
    James Kuyper
    Nov 4, 2011
Loading...

Share This Page