gpt4 book ai didi

c++ - 在 C++ 中读取原始字节数据

转载 作者:行者123 更新时间:2023-11-30 16:19:01 25 4
gpt4 key购买 nike

我有一个非常基本的问题。我想根据 Nrf52 BLE 设备接收到的 BLE 数据打开/关闭 LED。我的问题是数据(Received_Data)是原始字节数据形式(1 个字节),我不知道如何对其执行 if 语句,或将其转换为可以的形式。在下面的代码中我有:

                if (Received_Data > 50)
{
nrf_gpio_pin_toggle(LED_2);
}
end

如何让“Received_Data”在这样的 IF 语句中使用,以便可以将其读取为整数或十六进制数?

        case APP_UART_DATA_READY:
UNUSED_VARIABLE(app_uart_get(&data_array[index]));
index++;

if ((data_array[index - 1] == '\n') ||
(data_array[index - 1] == '\r') ||
(index >= m_ble_nus_max_data_len))
{
if (index > 1)
{
NRF_LOG_DEBUG("Ready to send data over BLE NUS");
NRF_LOG_HEXDUMP_DEBUG(Received_Data, index);

if (Received_Data > 50)
{
nrf_gpio_pin_toggle(LED_2);
}
end

这让我很头疼。我确信有人会在 5 秒内回答这个问题。我已经无法投入时间去挖掘所有相关的 C++ 文档来找到解决方案了。

最佳答案

根据你的问题

How can I let 'Received_Data' be used in an IF statement like this, so it can be read as an integer or a hex number?

来自您的评论

It is already defined as a uint8: uint8_t Received_Data[BLE_NUS_MAX_DATA_LEN];

Just want to check that the byte within the array is above or below a certain threshold, such as 50. What would be the syntax to do that with an IF statement?

Received_Data 是无符号 8 位整数的数组。在您提供的第一段代码中:

if (Received_Data > 50){
nrf_gpio_pin_toggle(LED_2);
}

Received_Data 衰减为指向数组第一个元素的指针。因此,您实际上是在指针和整数之间进行比较(ISO C++ 明确禁止这样做)。如果您想检查该数组的特定元素的值,那么您需要使用下标运算符对其进行索引,如下所示:

//byte_of_interest is some non-negative integer value that specifically represents
//the element in the array that you are interested in comparing with 50
if (Received_Data[byte_of_interest] > 50){
nrf_gpio_pin_toggle(LED_2);
}

同样,你也可以使用指针运算:

//byte_of_interest is an offset from the beginning of the array
//so its contents are located at the address to the beginning of the array + the offset
if (*(Received_Data + byte_of_interest) > 50){
nrf_gpio_pin_toggle(LED_2);
}

此外,我建议您将数组初始化为 0,以防止在填充数组之前出现误报(例如 uint8_t Received_Data[BLE_NUS_MAX_DATA_LEN] = {0};)

关于c++ - 在 C++ 中读取原始字节数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55747455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com