【问题标题】:How to concatenate multiple hex values to one如何将多个十六进制值连接到一个
【发布时间】:2019-09-21 23:03:01
【问题描述】:

我正在使用 QStringList 从配置文件中读取数百行/数千行。我想将每一行的 4 个字符串转换为 4 个十六进制值,将这些值连接到一个十六进制值并通过 UART 发送到(STM32)uC。

示例: 从配置中读取:1200,1200,1200,1200 -> 以逗号分隔:1200 1200 1200 1200 -> 转换为十六进制:04B0 04B0 04B0 04B0 -> 连接十六进制值:04B004B004B004B0强>

if(lines.at(i).contains(",")){
      while(lines.at(i+j) != "\n"){
      QStringList speed_chunks = lines.at(i+j).split(",");
      uart = speed_chunks.at(3)+speed_chunks.at(4)+speed_chunks.at(5)+speed_chunks.at(6)+"\0";

    m1 = speed_chunks.at(3).toInt();
    m1h = QString::number(m1, 16).toUpper();

    m2 = speed_chunks.at(4).toInt();
    m2h = QString::number(m2, 16).toUpper();

    m3 = speed_chunks.at(5).toInt();
    m3h = QString::number(m3, 16).toUpper();

    m4 = speed_chunks.at(6).toInt();
    m4h = QString::number(m4, 16).toUpper();

    uart_hex = m1h+m2h+m3h+m4h +"\0"; WRONG!!!
    //m1hm2hm3hm4h needed, not plus function!

qDebug()<<uart_hex;

m_serial.write(uart()); ?

                               }
                                 }

这是最简单的方法吗?非常感谢!

【问题讨论】:

  • 您的输入中总是有前导零吗?比如0001,0022,1111,0100?
  • 连接字符串很明显"0001" "0002""00010002"。但是“十六进制值”建议使用整数,而连接整数的意义要小得多。数字 01 与数字 1 相同。
  • 您好,1000和2000之间有不同的PWM值。PWM值是针对4个电机调速器的。每个电机速度控制器每 100 毫秒获得另一个值,因此可能有不同的组合:1245,1587,1698,1478....
  • 所以我想先将值更改为十六进制:1245 到 04DD,1587 到 0633... -> 然后连接到 04DD0633... -> 然后发送值。

标签: c++ qt hex


【解决方案1】:

要打印结果,您可以使用std::hexstd::stringstream 的组合:

std::stringstream stream;
QStringList items = lines.at(i+j).split(",");
for (auto str : items) {
    const auto trimmed = str.trimmed();
    const auto number = trimmed.toInt();
    stream << std::hex << number;
}

const auto result = stream.str();
std::cout << result;

这将打印:

4b04b04b04b0                                                                                                                                                                                                                                                 

您可以尝试将结果转换回整数。

【讨论】:

  • 非常感谢!我会试试看。关于通过 UART 向 uC 发送的另一个问题 - 4b0 4b0 4b0 4b0 它仍然是 8 字节(4b0 = 04b0?)或零将被删除,我的 uC 只收到 4b04 b04b 04b0(所以只有 6 字节长度)?
  • @Fracture 我不太确定。我刚刚用 RS232 模拟器做了一个测试,我收到了“4b04b04b04b0”
  • 错误1:聚合‘std::stringstream stream’类型不完整,无法定义std::stringstream流;
  • 错误2:‘cout’不是‘std’std::cout的成员
  • 我是否在 QT 中进行了转换或声明 std?怎么样?
猜你喜欢
  • 2017-08-26
  • 1970-01-01
  • 2016-07-25
  • 1970-01-01
  • 2018-07-16
  • 2016-08-07
  • 2018-07-26
  • 2023-02-20
  • 2013-04-18
相关资源
最近更新 更多