Convert a char array to uint8_t

2

I have the following array of characters:

char caracteres[10] = {'1', '2'};

And the next uint8_t (its size is 1 byte):

uint8_t resolucion;

What I want is to store the 12 (as a number) within the variable resolucion . I have tried some things but they have not worked for me. Any suggestions?

    
asked by Kane12 23.05.2018 в 12:21
source

2 answers

3

Assuming you have this:

char caracteres[10] = {'1', '2'};

If you have not already done so, you should end the string with ''0'' :

char caracteres[10] = {'1', '2', '
char caracteres[10] = "12";
' };

With what would be equivalent to this:

uint8_t resolucion = 0;
for( char* ptr = caracteres; *ptr; ++ptr )
{
  resolucion *= 10;
  resolucion += *ptr - '0';
}

The whole step is as simple as using a loop:

'9' - '0' = 9
'5' - '0' = 5
'1' - '0' = 1
'0' - '0' = 0

That is, it is iterated by the sequence of characters and each one is subtracted the digit %code% (do not forget that the character is the representation of a number). Reviewing an ASCII table is easy to see that:

char caracteres[10] = {'1', '2'};
    
answered by 23.05.2018 / 12:40
source
3

You can convert a character string to a number with the std::stoi ( s ) utility % tring to i nteger) present in the header <string> :

char caracteres[10] = {'1', '2'};
uint8_t resolucion = std::stoi(caracteres);

Keep in mind that std::stoi returns int no uint8_t , so there could be data narrowing, but if your resolución will always fit in 8bits it should not be a problem.

Also keep in mind that passing% co_of% non-transformable values to number can throw an exception std::stoi .

    
answered by 23.05.2018 в 12:45