C/C++ 整數(2進位/8進位/10進位/16進位)轉 字串

C/C++ 整數(2進位/8進位/10進位/16進位)轉 字串

C/C++ 整數(2進位/8進位/10進位/16進位)轉 字串


資料來源:https://mp.weixin.qq.com/s/lZ9SsObIMoncjs4ZoyLRlA

線上編譯:https://www.tutorialspoint.com/compile_c_online.php


code:

#include <stdio.h>
char *sky_itoa(int value, char *str, unsigned int radix)
{
	char list[] = "0123456789ABCDEF";
	unsigned int tmp_value;
	int i, j, k;
	
	if (NULL == str)
	{
		return NULL;
	}
	
	if (2 != radix && 8 != radix && 10 != radix && 16 != radix)
	{
		return NULL;
	}
		i = 0;
		k = 0;
		if (radix == 10 && value < 0) {
		tmp_value = (unsigned int)(0 - value);
		str[i++] = '-';
		k = 1;
	}
	else
	{
		tmp_value = (unsigned int)value;
	}
	
	do
	{
		str[i++] = list[tmp_value%radix];
		tmp_value /= radix;
	} while(tmp_value);
	str[i] = '\0';
	
	//翻转
	char tmp;
	for (j = k; j < (i+k)/2; j++)
	{
		tmp = str[j];
		str[j] = str[i+k-j-1];
		str[i+k-j-1] = tmp;
	}
	return str;
}

int main()
{
    int a = 1254545;
    char str[100] ={0};

    printf("二進制: %s\n",sky_itoa(a,str,2));
    printf("八進制: %s\n",sky_itoa(a,str,8));
    printf("十進制: %s\n",sky_itoa(a,str,10));
    printf("十六進制: %s\n",sky_itoa(a,str,16));
    return 0;
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *