Home > front end >  How to convert int32_t to int in c?
How to convert int32_t to int in c?

Time:08-16

How can I convert int32_t to int ?
For example:

int func(int32_t var) {
   int x = (..?) var;
   return x;
}

CodePudding user response:

Easy:

int func( int32_t var ) {
    return var;
}

Done.

CodePudding user response:

You did not specify what behaviour you want for values that can't be represented by an int.

If you're ok with implementation-defined behaviour and with the program crashing from an implementation-defined signal in that situation, then all you need is

int x = var;

Otherwise, you will need to handle negative values larger than INT_MIN and positive values larger than INT_MAX appropriately. These two constants are defined in limits.h.

CodePudding user response:

When int range is as wide or wider than int32_t, simply assign.

int func(int32_t var) {
 int x = var;
 return x;
}

When int range is narrower than int32_t, a cast will quiet warnings about narrowing.

int func(int32_t var) {
 int x = (int) var;
 return x;
}

In this 2nd case, it is unclear what OP wants should var exceed the int range. Perhaps limit?

#include <limits.h>
#include <stdint.h>

int func(int32_t var) {
  #if INT32_MAX > INT_MAX || INT32_MIN < INT_MIN
    if (var > INT_MAX) {
      return INT_MAX;
    }
    if (var < INT_MIN) {
      return INT_MIN;
    }
    return (int) var;
  #else
    return var;
  #endif
}
  • Related