I'm reading data from UART byte by byte. This is saved to a char. The byte following the start byte gives the number of subsequents bytes incoming (as a hexadecimal). I need to convert this hex number to an integer, to keep count of bytes required to be read.
Presently I'm simply type-casting to int. Here's my code:
char ch;
int bytes_to_read;
while(1){
serial_read(UART_RX, &ch, sizeof(char));
if(/*2nd byte*/){
bytes_to_read = (int)ch;
}
}
I read about strtol(), but it takes char arrays as input. What's the right way to do this?
Your question is unclear, but assuming that ch
is a hexadecimal character representing the number of bytes, then you could just use a simple function to convert from hex to int, e.g.
int hex2int(char ch)
{
if (ch >= '0' && ch <= '9')
return ch - '0';
if (ch >= 'A' && ch <= 'F')
return ch - 'A' + 10;
if (ch >= 'a' && ch <= 'f')
return ch - 'a' + 10;
return -1;
}
and then:
bytes_to_read = hex2int(ch);
ch
is really just a raw value (i.e. not a hex character) then your existing method should be fine:
bytes_to_read = (int)ch;
strtol
works on a string, ch
is a char
, so convert this
char to a valid string
char str[2] = {0};
char chr = 'a';
str[0] = chr;
and use strtol
with base 16
:
long num = strtol(str, NULL, 16);
printf("%ld\n", num);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With