Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
| From | Thad Smith <ThadSmith@acm.org> |
|---|---|
| Newsgroups | comp.lang.c |
| Subject | Re: left shift count >= width of type |
| Date | 2011-11-02 20:22 -0600 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <j8stsb$lge$1@speranza.aioe.org> (permalink) |
| References | <9hcichF56iU1@mid.individual.net> |
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
Back to comp.lang.c | Previous | Next — Previous in thread | Find similar | Unroll thread
left shift count >= width of type Alessandro Basili <alessandro.basili@cern.ch> - 2011-11-02 10:55 +0100
Re: left shift count >= width of type James Kuyper <jameskuyper@verizon.net> - 2011-11-02 07:34 -0400
Re: left shift count >= width of type Keith Thompson <kst-u@mib.org> - 2011-11-02 13:47 -0700
Re: left shift count >= width of type Alessandro Basili <alessandro.basili@cern.ch> - 2011-11-04 17:46 +0100
Re: left shift count >= width of type James Kuyper <jameskuyper@verizon.net> - 2011-11-04 13:12 -0400
Re: left shift count >= width of type Alessandro Basili <alessandro.basili@cern.ch> - 2011-11-05 19:17 +0100
Re: left shift count >= width of type Thad Smith <ThadSmith@acm.org> - 2011-11-02 20:22 -0600
csiph-web