简体   繁体   中英

Concatanation of strings and ints in C++. Conversion from ASCII to HEX

I've been banging my head against the wall trying lots of different methods for doing this but none of them seem to work correctly.

The commented out lines are the code in C# that i'm trying to re-write in C++. Any help would be much appreciated.

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;

    */
}

Thanks

Joe

I don't know exactly what your C# code does but for the second

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

doesn't look a million miles away. Similarly for the first

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

looks like it's close to what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM