sprintf does not give the expected result

0

I have variables of type Unsigned Long Int and would like to save its value in string , to perform checksum and send via serial communication.     void Payload (int long unsigned lastTime, float deltaOne, float deltaTwo, int factor) {

[...]
sprintf(buffer, "CAPTION,%u,%s,%s,%d," lastTime,deltaOne,deltaTwo,factor);
SendWithCS(buffer);
}

But the value converted from int to string is not the same. Example:

int long unsigned record = 11285600;
float delta1 = 50.2035;
float delta2 = 54.2035
int factor = 5;
Payload(record,delta1,delta2,factor);

Output:

CAPTION,22601,50.2035,54.2035,5,3F
    
asked by anonymous 16.02.2017 / 12:36

1 answer

1

The code has several errors, after you have cleaned them the wrong formatting. See existing options .

This is a C code compiled with C ++. These functions are avoided at idiom C ++.

The unsigned number was wrong, and the floating-point number was wrong.

#include <iostream>
using namespace std;

void Payload(unsigned long lastTime, float deltaOne, float deltaTwo, int factor) {
    char buffer[sizeof(unsigned long) + sizeof(float) + sizeof(float) + sizeof(int) + 13];
    sprintf(buffer, "CAPTION,%u,%.4f,%.4f,%d,", lastTime, deltaOne, deltaTwo, factor);
    printf("%s", buffer);
    printf("\nCAPTION,11285600,50.2035,54.2035,5,\n");
}

int main() {
    unsigned long record = 11285600UL;
    float delta1 = 50.2035;
    float delta2 = 54.2035;
    int factor = 5;
    Payload(record, delta1, delta2, factor);
}

See running on ideone . And No Coding Ground . Also I put it in GitHub for future reference .

    
16.02.2017 / 14:25