It depends on what you want the behaviour to be. An int
cannot hold many of the values that an unsigned int
can.
You can cast as usual:
int signedInt = (int) myUnsigned;
but this will cause problems if the unsigned
value is past the max int
can hold. This means half of the possible unsigned
values will result in erroneous behaviour unless you specifically watch out for it.
You should probably reexamine how you store values in the first place if you're having to convert for no good reason.
EDIT: As mentioned by ProdigySim in the comments, the maximum value is platform dependent. But you can access it with INT_MAX
and UINT_MAX
.
For the usual 4-byte types:
4 bytes = (4*8) bits = 32 bits
If all 32 bits are used, as in unsigned
, the maximum value will be 2^32 - 1, or 4,294,967,295
.
A signed int
effectively sacrifices one bit for the sign, so the maximum value will be 2^31 - 1, or 2,147,483,647
. Note that this is half of the other value.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…