Why not write the code like this?
I bring this up because we recently encountered a bug. We need to transmit the battery level to BT, and then BT displays the level on the phone. A problem we encountered is that if we transmit 100% of the level, the actual level displayed is 0.
We use a function like this, which has 3 parameters.
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
typedef unsigned char uint08;
typedef unsigned short uint16;
typedef long unsigned int uint32;
typedef unsigned long long uint64;
typedef unsigned int uint;
#define nullptr (void*)(0)
/******************************************************************************
* Descript: Converts a numeric value to a string in decimal format.
* Params:
* @str[OUT]--Converts the value of the input buffer.
* @dec[IN]--Decimal value.
* @num[IN]--The number of conversions. (num<=10)
* @isDropZero[IN]--Whether to discard zero or not.
* Return: The length of the converted string.Negative means failure.
* Others: None.
*******************************************************************************/
const uint32 Pow10Array[] = {1, 10, 100, 1000, 10000, 100000, 1000000,
10000000, 100000000, 1000000000};
int decToStr(char *str, uint32 dec, uint num, bool isDropZero)
{
uint08 temp;
uint32 value;
char *pTemp;
if(str == nullptr || num == 0) return 0;
if(num > 10) num = 10;
pTemp = str;
while(num--) {
value = dec/Pow10Array[num];
temp = value%10;
if(isDropZero && temp == 0) continue;
if(isDropZero) isDropZero = false;
*pTemp++ = '0'+temp;
}
if(pTemp == str) *pTemp++ = '0';
return (pTemp-str);
}
int main()
{
char buffer[64] = { };
int indicators = 1;
decToStr((char*)buffer, indicators, 3, true);
printf("%s\n", buffer);
return 0;
}
There is a num parameter in the function. If this parameter is not set correctly, it will be fatal. For example, if the number is 100 and I set this parameter to 2, the result will be like this.
The implementation of this function is quite good.
Of course, since it is a common problem.
But I wonder why they don't write code like this?
#include <stdio.h>
int main()
{
char buffer[64] = { 0 };
int indicators = 100;
sprintf(buffer, "%d", indicators);
printf("%s\n", buffer);
return 0;
}
Autumn
The recruitment has already begun. If you are not well prepared,
Autumn
It is difficult to find a good job.
Here is a big employment gift package for everyone. You can prepare for the spring recruitment and find a good job!