Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a ascii to int

Tags:

c

gcc 4.5.1 c89

I have a buffer that is filled with char characters. I need to compare them:

This is a sample contents of the buffer:

vote buffer [ 51 ]
vote buffer [ 32 ]
vote buffer [ 49 ]
vote buffer [ 32 ]
vote buffer [ 50 ]
vote buffer [ 32 ]
vote buffer [ 53 ]
vote buffer [ 32 ]

I am trying to get the int equivalent of these char's that are in the buffer to compare.

#define NUMBER_OF_CANDIDATES 7
if((vote_data.vote_buff[i] > NUMBER_OF_CANDIDATES || vote_data.vote_buff[i] < 1) {
    /* Do something */
}

As you can see it will never be true in the if statement as the range is far greater.

I have tried casting to (int). However, that didn't solve the problem.

I guess I could calculate from the ascii character set. However, I would rather not add more complexity if I cannot help it.

Many thanks for any advice,

like image 864
ant2009 Avatar asked Dec 17 '22 19:12

ant2009


1 Answers

If you just want to convert single characters to int, you can use c - '0' (which is equivalent to c - 48). If you want to convert strings of more than a single character, use sscanf()

like image 130
Sven Marnach Avatar answered Jan 08 '23 10:01

Sven Marnach