Search code examples
cstringuint8t

How to compare uint8_t array to a string in C?


I have an input which comes over UART.

uint8_t uartRX_data[UART_RX_BUF_SIZE]="";

I need to pass this data to a function. And, in this function I want to compare it with predefined strings like:

char RESP_OK[]                  = "OK";
char RESP_ERROR[]               = "ERROR";
char RESP_FAIL[]                = "FAIL";

What is the easiest way to do that?

EDIT: My problem is only about the data comparison and data passing to a function.


Solution

  • As long as the string in uartRX_data is NULL terminated you should be able to use strcmp like so:

    if (strcmp((const char *)uartRX_data, RESP_OK) == 0)
    {
      // handle OK
    }
    else if (strcmp((const char *)uartRX_data, RESP_ERROR) == 0)
    {
      // handle ERROR
    }
    else if (strcmp((const char *)uartRX_data, RESP_FAIL) == 0)
    {
      // handle FAIL
    }
    else
    {
      // handle unknown response
    }