Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex char to int conversion

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?

like image 780
Zaxter Avatar asked Nov 10 '14 08:11

Zaxter


2 Answers

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);


Note however that if 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;
like image 143
Paul R Avatar answered Oct 17 '22 03:10

Paul R


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);
like image 30
David Ranieri Avatar answered Oct 17 '22 01:10

David Ranieri