I want to put a number in char [] with the specified number of digits. When the number of digits is small, put a space (0x20) in front. Consider the environment where sprintf () cannot be used.
#include <stdio.h>
void SetValToCharArray(int val, int length, char *dstPtr)
{
int loop;
int digit;
int work;
work = val;
digit = 0;
while(work > 0) {
work /= 10;
digit++;
}
for(loop=0; loop < (length-digit); loop++) {
*dstPtr = ' ';
dstPtr++;
}
dstPtr += (digit - 1);
work = val;
for(loop=0; loop< digit; loop++) {
*dstPtr = (work % 10) + '0';
work /= 10;
dstPtr--;
}
}
int main(void) {
int val = 32768;
char szBuf[10];
memset(szBuf, 0, sizeof(szBuf) );
SetValToCharArray(val, /*length=*/7, &szBuf[0]);
printf("[%s]\n", szBuf); // [ 32768]
// for check
sprintf(szBuf, "%7d", val);
printf("[%s]\n", szBuf);
return 0;
}
http://ideone.com/5b6usH
It's not very clean coding, but it worked for the time being.
#include <stdio.h>
#include <stdbool.h>
void SetValToCharArray(int val, int length, char *dstPtr)
{
int loop;
int digit;
int work;
bool minus = false;
if (val < 0) {
minus = true;
val = (-val);
length--;
}
work = val;
digit = 0;
while(work > 0) {
work /= 10;
digit++;
}
for(loop=0; loop < (length-digit); loop++) {
*dstPtr = ' ';
dstPtr++;
}
if (minus) {
*dstPtr = '-';
dstPtr++;
}
dstPtr += (digit - 1);
work = val;
for(loop=0; loop < digit; loop++) {
*dstPtr = (work % 10) + '0';
work /= 10;
dstPtr--;
}
}
int main(void) {
int val = -271;
char szBuf[10];
memset(szBuf, 0, sizeof(szBuf) );
SetValToCharArray(val, /*length=*/7, &szBuf[0]);
printf("[%s]\n", szBuf); // [ 32768]
// for check
sprintf(szBuf, "%7d", val);
printf("[%s]\n", szBuf);
return 0;
}
http://ideone.com/W7BqSz
When the value is 0, it becomes as follows. I'm considering what I want to do.
[ ]
Implementation for the time being http://ideone.com/sIGRt4
Recommended Posts