Re: testing if just one bit is set...
On Nov 7, 12:59 pm, Jeff Schwab <j...@schwabcenter.com> wrote:
James Kanze wrote:
On Nov 6, 11:47 pm, Jeff Schwab <j...@schwabcenter.com> wrote:
Andrey Tarasevich wrote:
Well, unsigned values in C++ have one and only one [allowed]
representation. Which is why some people might find any
mention of "other representations" to be confusing
(equivalent or not).
We're not only discussing unsigned values.
Of course, the obvious solution is to cast to unsigned, and
then procede. Except that if he really is concerned with
signed values, casting to unsigned may change the bit
pattern (and thus the number of bits). A reinterpret_cast
involving references might do the trick (to make the
compiler access the value as if it were unsigned),
Is that UB? It reminds me of the old "access the other member
of the union" trick.
Yes and no. Casting a pointer or a reference is the
"officially" sanctionned way of type punning, but of course, you
don't get any guarantees with regards to the meaning of the
results in general. In this one particular case, you are
guaranteed that 1) the size of a signed integral type and its
corresponding unsigned is the same, and 2) that non-negative
values will have the same representation. So unless the sign
bit acts funny, you should be OK. (The C standard more or less
sanctions it, too, in that it allows you to pass signed integers
to match a "%x" format specifier.)
although even there, on at least one machine, unsigned is
implemented by simply masking out the sign bit (i.e.
UINT_MAX == INT_MAX).
What machine is that? I don't doubt that such platforms
exist, but that sounds more exotic than anything I've
targeted.
Unisys MCP. It's an interesting machine; it descends from the
old Burroughs line of machines, uses a stack instead of
registers, and has a tagged architecture; there's only one add,
sub, etc. instruction, which works for floating point or
integral values. I've not got access to one to do any testing,
but given the way it works, I suspect that an overflow in
integral arithmetic could lead to some very strange behavior.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34