【问题标题】:Reading raw byte data in C++在 C++ 中读取原始字节数据
【发布时间】:2019-04-18 13:49:09
【问题描述】:

我有一个非常基本的问题。我想根据 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++ 文档以找到解决方案的地步。

【问题讨论】:

  • 查看uint8数据类型。
  • @Thomas Nitpick:标准类型是uint8_t
  • 尝试if (Received_Data & LED_2),如果LED_2在字节内。
  • std::byte 表示原始字节。
  • Received_Data 是如何定义的?

标签: c++ c


【解决方案1】:

根据你的问题

如何让 'Received_Data' 在这样的 IF 语句中使用,所以 可以读成整数还是十六进制数?

来自你的 cmets

它已经被定义为一个uint8:uint8_t Received_Data[BLE_NUS_MAX_DATA_LEN];

只想检查数组中的字节是高于还是低于 某个阈值,例如 50。这样做的语法是什么 使用 IF 语句?

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

【讨论】:

    【解决方案2】:

    由于 Received_Data 是一个 uint8_t 数组,您可以直接访问单个字节:

    if (Received_Data[0] > 50)
    //or
    if (Received_Data[index] > 50)
    

    uint8_t 为 [0..255]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2011-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      相关资源
      最近更新 更多