问题
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.
回答1:
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
}
回答2:
Most conversions between the types char
, signed char
, unsigned char
, int8_t
and uint8_t
can be regarded as safe. These are the character types and come with various special exceptions that make them more "rugged" than other types.
Specifically, the character types:
- Cannot be misaligned.
- Cannot contain padding bits or trap representations.
- Have exceptions from the effective type/strict aliasing rules.
- Are always of size 1 byte.
Meaning you can do all manner of wild conversions between different character types. With a few exceptions:
- When going from unsigned to signed types the data may not necessarily fit and you'll overwrite the sign bit. This will potentially cause bugs.
- It is dangerous to "cast away"
const
orvolatile
qualifiers, if present.
Therefore it is safe to convert from uint8_t*
to char*
and de-reference the data as another type, (char*)uartRX_data
. Especially if you know that the uint8_t
array contains valid 7 bit characters only with MSB never set, and with a null termination in the end of the array.
来源:https://stackoverflow.com/questions/55967430/how-to-compare-uint8-t-array-to-a-string-in-c