Zaxter
Zaxter

Reputation: 3035

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?

Upvotes: 5

Views: 28100

Answers (3)

sila meg
sila meg

Reputation: 1

i think easy way :

unsigned char x = 0xff;
    int y = (int) x; 
    printf("Hex: %X, Decimal: %d\n",x,x);
    printf("y = %d",y);

for more info : https://www.includehelp.com/c/working-with-hexadecimal-values-in-c-programming-language.aspx

Upvotes: 0

David Ranieri
David Ranieri

Reputation: 41065

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

Upvotes: 3

Paul R
Paul R

Reputation: 213220

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;

Upvotes: 16

Related Questions