Char to Byte - Question

Good Morning,

well I've into array of char value for example:
Character
a[0] = '1' ;
a[1] = '4';

now I would like store 14 value inside byte variable for example b,

Could be fine: convert single value :
Dec Character
49 '1'

b = 49 - byte(a[0]) + 1 ?

How I can covert it ?

Thanks,
Gnux

use atoi()

http://www.cplusplus.com/reference/cstdlib/atoi/

byte b = (byte) atoi("14");

Note this will only work on number from 0 to 255

  char a[3] ;
  a[0] = '1' ;
  a[1] = '4' ;
  a[2] = 0 ; // null terminator
  byte b = atoi (a) ;

I like to do it by my own. So instead of use atoi() I build my own functions. In this case, with such an easy sting (only 2 chars) you don't even need a 'function'. So, you can do:

  char a[2] ;
  a[0] = '1' ;
  a[1] = '4' ;
  byte b =(a[0]-'0')*10 +  (a[1]-'0');

look that:
'0'-'0' = 0
'1'-'0' = 1
('6' - '0') * 10 = 6*10 = 60
etc.

You can take a look to the ASCII table.

I believe this answer your question, right?

Yes Is exatcly what I was thinking ... use :

byte b = atoi (a) ;

i think that is the most correct :slight_smile:

Thanks to all

gnux

@luisilva: What happens to the values 0-9 and 100-255? It appears that your algorithm only works for numbers with two digits, unless you require the value 1 to be stored at '0' '1'. Three digits won't work. It wouldn't be hard to create a function that would handle 1 to 3 digits using your approach.

Yes, for different number of digits the code must be different. With some loop, for example. But for such small number of digits we don't need to have a big function to do the conversion. And for some one that is starting he can learn what is ASCII, what is a char, a difference between '1' and 1, etc.