C ++中字符串和整数的连接。从ASCII转换为HEX

时间:2012-11-09 16:57:42

标签: c++ hex ascii

我一直在撞墙,试图采用许多不同的方法来做到这一点,但它们似乎都没有正常工作。

注释掉的行是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;

    */
}

由于

1 个答案:

答案 0 :(得分:0)

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

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

看起来并不是一百万英里之外。同样适用于第一个

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

看起来很接近你想要的东西。