5
votes

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?

3
Can you provide an example? How is the hex number encoded in the byte? - Joni
Does "as a hexadecimal" mean it's coming as text, in hexadecimal notation? I ask because many people here seem to say "hex" when they mean "binary", i.e. as raw bytes. - unwind
which hex number you want to convert?mention it clearly - Aadil Ahmad
@user3490458: in that case your code is already doing the right thing, i.e. just casting the char to an int - so what's the actual problem ? - Paul R
@user3490458 Do you get this 0x03 really as 4 characters 0, x, 0 and 3 or as one byte with the representation 0x03 and the value 3? Be sure you are clear about the distinction of value and representation. - glglgl

3 Answers

11
votes

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
bytes_to_read = (int)ch;
3
votes

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

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