Hello All,
I have a bit of a strange one here and I just can't seem to find a solution. I use sprintf() to format strings which I then send out a SCI port a little later. My problem is one particular string that I build has an incorrect number in it after sprintf() is complete.
typedef struct MOT_PARAM{...unsigned int BaudRate; //Baudrate setting between Main and Interface PCB...}mot_param;mot_param UA_Param;unsigned char debug_buf[64];size = sprintf((char *)debug_buf, "SB%d\r", (unsigned)UA_Param.BaudRate);
So here is the issue:
if UA_Param.BaudRate = 4800 or 9600 or 19200 then he string created is always correct i.e.
SB4800\r
SB9600\r
SB19200\r
However when UA_Param.BaudRate is greater than 19200 (such as 38400, 57600 & 115200) then the output string has the negative value of the Baudrate i.e.
So if UA_Param.BaudRate = 38400 i get SB-27136\r but it should be SB38400\r
What I cannot figure out is why any number larger than 19200 is being converted incorrectly. Does anyone have any ideas?
Details:
Target CPU - DSC56F8323
Codewarrior 8.1.1a for the DSC56F8000E
My Desktop OS - Win XP SP3
Thanks in advance for any help.
Solved! Go to Solution.
Hello,
Additionally, a value of 115200 would exceed the bounds of an unsigned int, and would require a long integer to handle. Another approach would be to handle the value as 96, 192, 384 .. 1152, and add the final two zeros as ASCII characters.
Maybe "SB%u00\r",
Regards,
Mac
Printf conversion type character 'd' is for signed integers. 'u' - for unsigned. You should change %d to %u.
Printf has no way to check what you are pushing to the stack in parameter list. Printf uses format string as a declaration what are you passing to it.
Hello,
Additionally, a value of 115200 would exceed the bounds of an unsigned int, and would require a long integer to handle. Another approach would be to handle the value as 96, 192, 384 .. 1152, and add the final two zeros as ASCII characters.
Maybe "SB%u00\r",
Regards,
Mac
Hello All,
Thanks for the help. I found bigmac's solution to be the best. I had one of those "duh" moments when he reminded me that 115200 is to big for an unsigned integer.
I already recieve the baud rate in as an ASCII string via the serial port so I have simply dropped the '0' off the end then I do an atoi() and this solved the problem. When I report the data back out the suggested "SB%u00\r" is perefect.
Thanks again.
Or simply save the baudrates as strings
It will mean an immense saving of flash memory. Am I nuts? No... because if they were saved as strings in the first place, you wouldn't need the horrible sprintf() function, nor would you need your own less horrible int-to-string function.