bug?

David Berthelot davidb@Magma-DA.COM
Mon Jun 18 10:06:00 GMT 2001


Ingo Krabbe wrote:

> On Fri, 15 Jun 2001, Ben Kohlen wrote:
>
> > I am expecting that when I shift right, I will always
> > get zeroes in from the left, but when I use data types
> > less than 32 bits, this is not always the case.
> >
> > Example:
> > ...
> > unsigned short s = 0xcc55;
> > printf("%x\n", (s<<8)>>8);
> > ...
> > yeilds the output "cc55" where as I was expecting
> > "55".
> >
>
> I don't think thats a bug, it is more a question of flavour, of course
> it would be very nice to fill 0 into the upper bits. It may be better to
> mask them out:
> #define CLEAR_UPPER_BITS(n,x) \
>         ((n<sizeof(x)*8) ? x&(~((~(x^x))<<(8*sizeof(x)-n))):0)
>
> This is machine and (numeric) type independent masking out of n upper
> bits. For smaller types we can use a 0 instead of x^x. There may be a more
> optimized solution ? We can also give a 0 in the right length to the
> algorithm:
> #define CLEAR_UPPER_BITS(n,x,null) \
>         ((n<sizeof(x)*8) ? x&(~((~(null))<<(8*sizeof(x)-n))):0)
>
> Has anyone a better solution ?
>
> CU INGO

Ok may be I don't get it, but for me it seems rather complicated to me,
I don't even understand the x^x (x power x ?).

I propose that:

x = number to clarify upper bits,
n = index of the first byte to clear (0 .. 2^p-1 for a type with p bytes)

#define CLEAR_UPPER_BITS(n,x)\
                                               (x&((1<<(n))-1))

Simple no ?

By the way, it's not the shift that causes problems, it's the printf that
assumes its arguments to be ints (that's in the specs). With addition
you would have the same problem:

short x = 0x7fff;

printf("%x\n", x+x+x);

will display:
0x17ffd (and that's out of the bounds for a short).

David



More information about the Gcc-help mailing list