Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

type casting unsigned integer

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 clamping the values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading