【问题标题】:Concatanation of strings and ints in C++. Conversion from ASCII to HEXC++ 中字符串和整数的连接。从 ASCII 转换为 HEX
【发布时间】:2012-11-09 16:57:41
【问题描述】:

我一直在用头撞墙,尝试了很多不同的方法来做到这一点,但似乎没有一个能正常工作。

注释掉的行是我试图用 C++ 重写的 C# 代码。 任何帮助将不胜感激。

void sendCommand(string command)
{
    //Convert.ToString((8 * startBit) + "4" + command);
    char buffer[50];
    sprintf(buffer, "%d", (8 * startBit));
    motor.printf("sendBuffer: %d\r\n", buffer);
    startBit = 1 - startBit;
    motor.printf("%s%c%s\n\r", buffer, "4", command);
    return;
}

string strAcceleration(int acceleration)
{
    //string accelerationHex = acceleration.ToString("X");
    //accelerationHex = accelerationHex.PadLeft(8,'0');
    char buffer[50];
    sprintf(buffer, "%00000000X", acceleration);
    motor.printf("acc: %s", buffer);
    return buffer;
}

string strSpeed(int speed)
{
/*
    string speedHex = null;
    if (speed == 0) speedHex = "0";
    else if (speed > 0) speedHex = speed.ToString("X");
    else speedHex = 0xFFFFFFFF + speed.ToString("X");

    if(speedHex.Length == 1) speedHex = "0000000" + speedHex;
    if(speedHex.Length == 2) speedHex = "000000" + speedHex;
    if(speedHex.Length == 3) speedHex = "00000" + speedHex;

    return speedHex;

    */
}

谢谢

【问题讨论】:

  • 这个也应该用C#标记
  • 您能否澄清您的 C# 注释://Convert.ToString((8 * startBit) + "4" + command); - 你的意思是 Convert.ToString(8 * startBit) + "4" + command 吗?

标签: c++ hex ascii


【解决方案1】:

我不知道你的 C# 代码究竟做了什么,但第二个

sprintf(buffer, "%08X", acceleration);

看起来并不在一百万英里之外。第一个类似

std::ostringstream buffer;
buffer << (8 * startBit) <<  "4" << command;
std::string motor = buffer.str();

看起来很接近你想要的。

【讨论】:

  • 我更愿意使用 iostreams 来做所有事情,但由于原始软件使用 printf(甚至定义为成员函数!)所以我会保持相同的风格并使用 sprintf(buffer, "%d4 %s", 8*startBit, 命令);
猜你喜欢
  • 2013-04-01
  • 2013-02-08
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多