Fitzchak Yitzchaki
Fitzchak Yitzchaki

Reputation: 9163

What is the difference between Int32 and UInt32?

What is the difference between Int32 and UInt32?

If they are the same with capacity range capabilities, the question is for what reason UInt32 was created? When should I use UInt32 instead of Int32?

Upvotes: 25

Views: 99072

Answers (5)

Otávio Décio
Otávio Décio

Reputation: 74300

UInt32 does not allow for negative numbers. From MSDN:

The UInt32 value type represents unsigned integers with values ranging from 0 to 2 to the power of 32 or 2**32 (which equals to 4,294,967,295).

Upvotes: 52

fen
fen

Reputation: 371

uint32 is an unsigned integer with 32 bit which means that you can represent 2^32 numbers (0-4294967295).

However, in order to represent negative numbers, one bit of the 32 bits is reserved to indicate positive or negative number. this leaves you with 2^31 possible numbers in the negative and also in the positive. The resulting range is -2147483648 to 2147483647 (positive range includes the value 0, hence only 2147483647). This representation is called int32.

You should choose unsigned for numbers which can't get negative by definition since it offers you a wider range, but you should keep in mind that converting from and to int32 is not possible since int32 can't hold the range of uint32 and vice versa.

Upvotes: 11

Matt H
Matt H

Reputation: 7389

uint32 is unsigned 32-bit integer. It can't be used to represent negative numbers but can hold greater positive numbers.

Upvotes: 2

Robby Wasabi
Robby Wasabi

Reputation: 117

There is no difference between them.

The difference is how it is represented, such as via printing to terminal.

For example, and sticking with 8 bit values for simplicity:

  • 255 is 0xff, and -1 is also 0xff.
  • Interpret -1 as, "One to the left of zero", whereas +1 is, "One to the right of zero".
  • -1 + -1 = -2, which is, "Two to the left of zero", which is also 0xfe. Well, if we convert that to unsigned math, then, it becomes 0xff + 0xff = 0xfe.

So you see, there is no difference between signed and unsigned, it's only how we represent them in the end that makes the difference, and in this case, the type indicates how it is represented.

Signedness becomes important when the compiler has to cast from a smaller size to a bigger via sign extension. So in this case, it's important to indicate a type so that the compiler can do the right thing.

Upvotes: -4

Randy Minder
Randy Minder

Reputation: 48522

An integer is -2147483648 to 2147483647 and an unsigned integer is 0 to 4294967295.

This article might help you.

Upvotes: 16

Related Questions