"Nico Heinze" <[EMAIL PROTECTED]> wrote:
> "Rayne" <ghcgwgwg@> wrote:
> > Is there a way to extract the k most significant bits of
> > a 64-bit integer,

How are you storing that integer? C90 does not have a native
64-bit integer type, though C99 and many implementations
support unsigned long long. Many other implementations have
'inventions', e.g. __int64.

It's more robust to think of integer values, than integer
representations (in particular size.) If x is unsigned and
has at least 64 value bits, then x >> (64 - k) should do.

> > i.e. if k = 3, and the integer is
> > 1011100...001 in binary, then I get the first 3 bits 101
> > and read that as 5? I thought of using the right-shift
> > bitwise operator >>, but that works only for 8-bit
> > integers, right?
> 
> It should work for every integer data type your compilers
> supports.

Yes. However, realise that right shifting negative numbers
is implementation defined. Sign bit propagation on two's
complement machines is commonly expected, but not guaranteed
by the language.

Also note that you cannot right shift on or beyond the width
of the integer type. [Note that 'width' is independant of
padding bits.]

> Otherwise it's not allowed to call itself a C compiler,
> only to be named as a "compiler which compiles something
> which looks like C but actually isn't".
> 
> So don't worry, it should work. Just be careful to
> declare your 64-bit integer as "unsigned", otherwise you
> _may_ have to deal with negative numbers, and then things
> become complicated: if I recall correctly (I only recall
> that with the original K&R C this was the case), it's
> undefined how ">>" behaves when being used on negative
> integers:

It's implementation defined.

Left shifting a negative value has undefined behaviour.
Left shifting a signed type with a positive value, where
the mathematical shifted value cannot be represented is
also undefined. [e.g -1 << 1 and INT_MAX << 1 are both
undefined.]

> at least with K&R conformant software a compiler was
> allowed to define for itself whether a negative number
> as an operand for ">>" the negative sign would be kept
> or not.

Right shifting a negative value is implementation defined,
but the choice for an implementation is not restricted to
whether the sign bit propagates.

-- 
Peter

Reply via email to