Home > Enterprise >  type casting unsigned integer
type casting unsigned integer

Time:10-25

Consider val being a user input. I expect val to be between 0-65535

Instead of checking if val is not withing acceptable range before denying it, I was wondering if

is this :

uint16_t count = atoi(val);

the same as this :

uint16_t count = (uint16_t)atoi(val);

Is this an acceptable way of "securing" the user input? I do not intend to send a feedback to the user, I just want to make sure it won't explode if someone submits -123 or 999999. It does not matter if count equals 2 because someone submitted 65538

CodePudding user response:

Is this:

uint16_t count = atoi(val);

The same as this:

uint16_t count = (uint16_t)atoi(val);

They are the same. For the former, by assigning an int to a uint16_t, it is being implicitly converted anyway.

Since a uint16_t cannot contain any more than 65536 or less than 0, this is a safe way of wrapping the values, as the conversion takes the modulo.

CodePudding user response:

They are almost the same. The C standard’s specifications of how they will behave in execution are the same, and the C standard does not specify any difference between them other than the grammar, but neither does it require implementations to treat them identically in all regards.

For example, a compiler or code analyzer might warn you that uint16_t count = atoi(val); potentially alters a value during assignment while it lets uint16_t count = (uint16_t)atoi(val); pass without warning because a cast is usually taken as an indication that the programmer deliberately wants a conversion.

  •  Tags:  
  • c c
  • Related