Re: signed extended bitvalues ? (int x : 1; has value -1 !)
mario semo wrote:
is there any way to avoid sign extension of bitvalues?
When i use
int x : 1;
x=1;
then x has the value of -1 (0xffffffff).
Well, of course, except that it probably isn't 0xfffffff. The reason is that
a signed value's highest bit has the value -2^n, i.e. that it is negative.
template <class BaseInt>
class Foo
{
[...]
void bar()
{
BaseInt bitfield = x1 << 0
| x2 << 1
| x3 << 1
| x4 << 1
;
Since BaseInt is signed, so is bitshift arithmetic. You probably want to
avoid this, because you need precise unsigned arithmetic when assembling
bits. Firstly, let me stress the point that I would try to avoid signed
numbers when fiddling with single bits myself. Otherwise, you have a simple
chance: you simply map BaseInt to its unsigned type for internal use and
manipulation.
// traits base template (unused as is)
template<typename Integer>
struct IntegerTraits;
// specialisation for int and unsigned
template<>
struct IntegerTraits<int>
{ typedef unsigned UnsignedType; };
template<>
struct IntegerTraits<unsigned>
{ typedef unsigned UnsignedType; };
Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932