My apologies if the question seems weird. I'm debugging my code and this seems to be the problem, but I'm not sure.
Thanks!
You can convert an int to an unsigned int . The conversion is valid and well-defined. Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)
To convert a signed integer to an unsigned integer, or to convert an unsigned integer to a signed integer you need only use a cast. For example: int a = 6; unsigned int b; int c; b = (unsigned int)a; c = (int)b; Actually in many cases you can dispense with the cast.
The utoa() function coverts the unsigned integer n into a character string. The string is placed in the buffer passed, which must be large enough to hold the output. The radix values can be OCTAL, DECIMAL, or HEX.
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.
Unsigned int can be converted to signed (or vice-versa) by simple expression as shown below :
unsigned int z; int y=5; z= (unsigned int)y;
Though not targeted to the question, you would like to read following links :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With