Search code examples
cintegerbit-shiftshortatoi

How to convert int to short int in C?


Let's say I've got a char array[5] = {'1','2','3','4','\0'};.

If I want the integer, I can simply use the atoi()-function:
int num = atoi(array);

How could I retrieve the value as short/short int?

Of course, it's given that the value fits in a short.

Do I need to call atoi() and work it out with bitshifting? I'm not quite familiar with that, though.


Solution

  • There is no ascii to short function, https://en.cppreference.com/w/c/string/byte/atoi only lists atoi for ascii to int, atol for ascii to long and atoll for ascii to long long.

    But you can use atoi to convert to int, then just cast to short. Of course this will not check if the number is in the range of a short. You might need to check that yourself with something like SHRT_MIN <= i && i <= SHRT_MAX.

    int num = atoi(array);
    short s = (short)num;
    

    or just directly convert:

    short s = (short)atoi(array);
    

    As others suggested you don't need the explicit cast, but it might help better see what is going on here.

    short s = atoi(array);  // Implicit cast