4

This is probably a really silly question to experienced C++ developers, but what is the purpose of casting a -1 to uint32? I am translating a program from C++ to C# and there are many occasions when I see something like this:

static const uint32 AllTypes = static_cast<uint32>(-1);

What exactly does this do? How can the same be accomplished in C#?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
SvalinnAsgard
  • 225
  • 3
  • 10
  • I agree with Magnus, make `static_cast` vs. `dynamic_cast` a separate question. – CodesInChaos Jan 29 '12 at 11:20
  • 1
    Both questions are duplicates: http://stackoverflow.com/questions/28002/regular-cast-vs-static-cast-vs-dynamic-cast and http://stackoverflow.com/questions/809227/is-it-safe-to-use-1-to-set-all-bits-to-true – rve Jan 29 '12 at 11:25
  • 1
    you may find `std::numeric_limits::max()` more self-documenting. – justin Jan 29 '12 at 11:32
  • Thanks all for such quick replies. I will keep all that in mind next time--the static versus dynamic question is not too important to me, but rather just a curiousity. – SvalinnAsgard Jan 29 '12 at 11:32

3 Answers3

4

On systems using two's complement, casting -1 to unsigned gives the highest value an unsigned number can represent.

In C# you can use unchecked((UInt32)-1) or better: UInt32.MaxValue. This is well defined behavior, and works on all CPU architectures.

According to the thread rve linked, casting -1 to unsigned results in all bits being set on all architectures in C++.

Community
  • 1
  • 1
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
  • 1
    It sets all bits to 1 (= highest number) and it works on all machines, not only 2s complement. See http://stackoverflow.com/questions/809227/is-it-safe-to-use-1-to-set-all-bits-to-true – rve Jan 29 '12 at 11:22
  • Ah, thank you for the quick reply. That answers my question perfectly. – SvalinnAsgard Jan 29 '12 at 11:30
2

How can the same be accomplished in C#

uint AllTypes = uint.MaxValue;
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
1

I guess it's used to have all bits to 1. Useful when we use tagged data. Probably each elementary type it's given a bit, and 'complex' types (arrays, for instance) get their own.

CapelliC
  • 59,646
  • 5
  • 47
  • 90