Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast or convert an unsigned int to int in C?

Tags:

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!

like image 265
Eric Brotto Avatar asked Feb 26 '11 20:02

Eric Brotto


People also ask

Can you cast an int to an unsigned int c?

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.)

How do I cast an unsigned int to signed int?

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.

How do I turn an unsigned int into a string?

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.


2 Answers

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.

like image 138
Chris Cooper Avatar answered Sep 21 '22 13:09

Chris Cooper


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 :

  • signed to unsigned conversion in C - is it always safe?
  • performance of unsigned vs signed integers
  • Unsigned and signed values in C
  • What type-conversions are happening?
like image 27
Saurabh Gokhale Avatar answered Sep 25 '22 13:09

Saurabh Gokhale