IntToString

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
<pre class="cpp" name="code">void IntToStr(int iValue, char *strOutput)
{
	sprintf(strOutput, "%d", iValue);
}

 

void IntToStr(int iValue, char *strOutput)
{
	int i = 0;
	int len = 0;
	int tmp = 0;
	int bNegative = 0; 

	tmp = iValue;
	while (tmp / 10 != 0)
	{
		len++;
		tmp /= 10;
	}
	if (abs(iValue) >= 0)
	{
		len++;
	}
	
	if (iValue < 0)
	{
		bNegative = 1;
		iValue = -iValue;
		strOutput[0] = '-';
	}		
	for (i = 0; i < len; i++)
	{ 
		strOutput[i + bNegative] = (char)(iValue/pow((double)10, len-1-i)) + '0';
		iValue %= (int)pow((double)10, len-1-i);
	}
	strOutput[i + bNegative] = '\0';
	
}

void ReverseString(char *s)
{
	char *left = NULL;;
	char *right = NULL;
	char c;
	int len = strlen(s);
	
	for (left = s, right = s + len - 1; left <= right; 
		left++, right--) {
		c = *left;
		*left = *right;
		*right = c;
	}
}

void itoa0(int n, char s[])
{
	int i, sign;

	if ((sign = n) < 0)
		n = -n;
	i = 0;
	do {
		s[i++] = n % 10 + '0';
	} while ((n /= 10) > 0);
	if (sign < 0)
		s[i++] = '-';
	s[i] = '\0';

	ReverseString(s);
}

void itoa(int n, char s[])
{
	static int i;

	if (n / 10) {
		itoa(n / 10, s);
	} else {
		i = 0;
		if (n < 0) {
			s[i++] = '-';
		}
	}
	s[i++] = abs(n) % 10 + '0';
	s[i] = '\0';
}

void itos(int num, char *buf)
{
	int i = 0;

	if (num / 10) {
		itos(num / 10, buf);
		for(i = 0; buf[i] != '\0'; i++)
			;
	} else {
		i = 0;
		if (num < 0)
			buf[i++] = '-';
	}

	buf[i] = abs(num) % 10 + '0';
	buf[i + 1] = '\0';
}

void xtos(unsigned int num, char *buf)
{
	int i;

	if(num < 16){
		if(num < 10){
			buf[0] = num + '0';
		}else{
			buf[0] = num - 10 + 'a';
		}

		buf[1] = '\0';

		return;
	}

	xtos(num / 16, buf);

	for(i = 0; buf[i] != '\0'; i++);

	if((num % 16) < 10){
		buf[i] = (num % 16)	+ '0';	
	}else{
		buf[i] = (num % 16) - 10 + 'a';		
	}

	buf[i + 1] = '\0';
}

void IArrToStr(int *iArr, int iElemNum, char *strOutput)
{
	int len = 0;
	int i = 0;
	char *pOutPos = strOutput;
	char strVal[6] = {0};

	for (i = 0; i < iElemNum; i++)
	{
		//IntToStr(iArr[i], strVal);
		//itoa(iArr[i], strVal);
		//itoa0(iArr[i], strVal);
		itos(iArr[i], strVal);
		len = strlen(strVal);
		strcpy(pOutPos, strVal);
		pOutPos += len;
		*pOutPos++ = ',';
	}
	*pOutPos = '\0';
}

int main()
{
	int arr[] = {234, 12345, -345, 234, -9234, 100, 200, 0, 13, -242};
	char str[6] = {0};
	char strOutput[64] = {0};
	int len = sizeof(arr) / sizeof(arr[0]);

	for (int i = 0; i < len; i++)
	{
		IntToStr(arr[i], str);
		printf("%s\n", str);
	}

	IArrToStr(arr, len, strOutput);
	printf("%s\n", strOutput);

	system("pause");
	return 0;

} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值