How to convert char array to byte?

atoi() function requires that --
(1) The array containing the elemnets must be char type.
(2) Each elemnt should be an ASCII code for the numberals 0 to 9.
(3) For example: Given the number 255, the array declaration should be:

char myNum = {0x32, 0x35, 0x35, 0x00};
or
char myNum = "255";

The @mirage's following declaration meets Step-(1) only. Therefore, atoi() function will extract 0 (zero) and not the number 255.

char high[4] = "0xff";

Given in Post-1:

char high[] = "0xff";

The strtoul() function correctly extracts the number 255. Would appreciate to heard why the function works when the array contains a non-digit symbol 'x'. As I understand, the parsing should stop at x; as a result, the function should produce 0.

The strtol() and strtoul() functions are specially designed to interpret numbers with different radixes.
There are rules for binary, hex and octal notation in C++, and they are implemented so that they can be interpreted.

See strtol() functions documents.
https://www.cplusplus.com/reference/cstdlib/strtol/

Ooops


Thanks for the link.
The strtoul() function is really smart to sense that 0x is the pre-fix for a hexadecimal number and accordingly, it correcltly converts this string: "0xff" into a valid number (255 in decimal and 0xFF in hex).

Oooppps

The function is smart :slight_smile:

The doc states

If the base value is between 2 and 36, the format expected for the integral number is a succession of any of the valid digits and/or letters needed to represent integers of the specified radix (starting from '0' and up to 'z' /'Z' for radix 36). The sequence may optionally be preceded by a sign (either + or - ) and, if base is 16, an optional "0x" or "0X" prefix.

char myNum[] = {0x32, 0x35, 0x35, 0x00};
or
char myNum[] = "255";

Better :wink:

Noted with thanks.