1 << BITS_PER_UNIT
Alexandre Oliva
oliva@dcc.unicamp.br
Mon Oct 26 02:24:00 GMT 1998
Richard Earnshaw <rearnsha@arm.com> writes:
>> It regards the use of (1 << BITS_PER_UNIT), usually when computing a
>> bit mask with (1 << BITS_PER_UNIT) - 1, when BITS_PER_UNIT is equal to
>> the number of bits in a HOST_LONG_INT.
> Or just use (2 << (BITS_PER_UNIT - 1))
> Same result, but no warning.
Did you run:
#include <stdio.h>
#define BITS_PER_UNIT 8
main() {
printf("%x %x\n",
(1 << BITS_PER_UNIT) - 1,
(2 << (BITS_PER_UNIT - 1)));
}
It prints:
ff 100
They don't seem equal to me :-)
And, worse yet, no warning! :-D
AFAIK, shifts larger than promoted type of the shifted value produce
undefined results. The C++ Standard states this, but I'm not sure
about C. Anyway, we shouldn't rely on that...
If we can assume that the host int type is at least as large as
BITS_PER_UNIT, then we can make it portable by using:
(((1 << (BITS_PER_UNIT - 1)) - 1) << 1) + 1
And, if we can't assume that, we might just abort the compilation,
saying that such (cross-)build is not supported.
--
Alexandre Oliva
mailto:oliva@dcc.unicamp.br mailto:oliva@gnu.org mailto:aoliva@acm.org
http://www.dcc.unicamp.br/~oliva
Universidade Estadual de Campinas, SP, Brasil
More information about the Gcc
mailing list