Jo Michaelis
Jo Michaelis

Reputation: 66

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.

Upvotes: 0

Views: 2358

Answers (2)

0___________
0___________

Reputation: 68034

A safer version than simple cast.

#include <stdlib.h>
#include <limits.h>

short getshort(const char *num, int *errcode) 
{    
    int result = atoi(num);

    if(errcode)
    {
        *errcode = 0;
        if(result > SHRT_MAX) *errcode = 1;
        else if(result < SHRT_MIN) *errcode = -1;
    }
    return result;
}

Upvotes: 1

Werner Henze
Werner Henze

Reputation: 16781

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

Upvotes: 5

Related Questions