C> string operation> Implementation to put in char [] with specified digit

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.

try1 (positive numbers only)

#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

try2 (for negative numbers)

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

Remarks

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

C> string operation> Implementation to put in char [] with specified digit
How to convert / restore a string with [] in python
How to delete the specified string with the sed command! !! !!
How to use python put in pyenv on macOS with PyCall
Put postfix 2.11 in source with ansible
Try to put data in MongoDB
How to wrap C in Python
6 ways to string objects in Python
Segfault with 16 characters in C language
(Matplotlib) I want to draw a graph with a size specified in pixels
[C language] I want to generate random numbers in the specified range
[With commentary] Solve Fizz Buzz (equivalent to paiza rank C) in Python