Re: a DWORD with all bits set...
- From: "Doug Harrison [MVP]" <dsh@xxxxxxxx>
- Date: Tue, 02 Jun 2009 13:36:20 -0500
On Tue, 02 Jun 2009 13:43:45 -0400, r norman <r_s_norman@xxxxxxxxxxx>
wrote:
It works to the extent ~0 == -1, which it does under two's complement.
Using -1 is preferred because it says exactly what is intended, because the
result of converting -1 to any unsigned type T is the largest value of T,
the value with all bits set.[*] For ~0 to say exactly what is intended, you
would have to write:
DWORD x = ~DWORD(0);
[*] Note that -1 works because the result of converting a negative number x
to an unsigned type T is the least value of T congruent to x modulo 2^N,
where N is the number of bits in T. This implies T(-x)+x == 0, and in
particular, T(-1)+1 == 0.
I disagree. The purpose of setting all bits probably relates to
bitwise operations. In any event, even referring to that situation
refers to bitwise notions. So a bitwise operator like ~0 is
preferable to an arithmetic operation like -1 that works only because
the computer happens to use two's complement for negative numbers.
Yes, I am an old guy and have a memory going back some 50 years when
there really were alternative ways of expressing negative numbers.
You need to study my post. Despite my stating it correctly, you've got the
two's complement issue exactly backwards. The representation of -1 does not
matter for the purpose of the signed->unsigned conversion rule, which I
gave in the [*] section. However, the representation of ~0 does matter for
the purpose of defining an unsigned value with all bits set, and I gave the
reason in my first sentence. I went on to show how to use ~0 in the
foolproof way and demonstrated it's more work and requires you to keep the
types on the LHS and the RHS in sync. OTOH, it is universally true that for
any unsigned type T, the following statement initializes x with the largest
value of T, the value with all bits set:
T x = -1;
--
Doug Harrison
Visual C++ MVP
.
- Follow-Ups:
- Re: a DWORD with all bits set...
- From: r norman
- Re: a DWORD with all bits set...
- References:
- a DWORD with all bits set...
- From: .rhavin grobert
- Re: a DWORD with all bits set...
- From: Doug Harrison [MVP]
- Re: a DWORD with all bits set...
- From: r norman
- a DWORD with all bits set...
- Prev by Date: Re: a DWORD with all bits set...
- Next by Date: Re: a DWORD with all bits set...
- Previous by thread: Re: a DWORD with all bits set...
- Next by thread: Re: a DWORD with all bits set...
- Index(es):
Relevant Pages
|