天天看點

【造輪子】實作 atoi、itoa 函數1. atoi 函數2. itoa 函數

1. atoi 函數

1.1 函數簡介

atoi 函數為 C 庫函數之一,用于把字元串轉換為對應的整形十進制數字。

  • 原型:

    int atoi (const char* str);

  • 所屬頭檔案:<stdlib.h>
  • 功能:把

    str

    指向的字元串轉換為對應的整形十進制數字。
  • 傳回:轉換得到的數值。

1.2 函數說明

  • 在原 atoi 函數中,如果字元串含非數字字元即非 ‘0’ - ‘9’ 字元,則把非數字字元前的子字元串進行整形轉換并傳回。但個人認為,如果字元串含非數字字元時,函數應抛出異常。
  • 字元串中的數字字元前可能存在空格,這時應把這些空格剔除。
  • 在進行轉換前,需要對字元串進行符号判定,字元串可能使用 “+” 或 “-” 來表示數值的正負。

1.3 函數實作

int atoi(const char* str)
{
    enum number
    {
        Positive,
        Negative,
    };

    // 剔除空格
    while (*str == ' ')
    {
        str++;
    }

    int num = 0;
    enum number flg = Positive;

	if (*str == '+')
	{
		str++;
	}
	else if (*str == '-')
    {
        flg = Negative;
        str++;
    }

	while (*str >= '0' && *str <= '9')
	{	
		if (Positive == flg)
		{
		    num = num * 10 + (*str - '0');
		}
		else if (Negative == flg)
		{
		    num = num * 10 - (*str - '0');
		}
		str++;
	}
	
	return num;
}
           

2. itoa 函數

2.1 函數簡介

itoa 函數為非 C 庫函數,在 Linux 下無定義,隻在 window 下的 vs 庫中有定義,是用于把整形十進制數轉換為任意進制的數值并以字元串形式呈現。在 Linux 中建議使用 sprintf 函數進行整形向字元串轉換。

  • 原型:

    int itoa (int num, char* str, int radix);

  • 功能:把

    num

    radix

    進制進行轉換,轉換結果儲存到

    str

    指向的記憶體中。
  • 傳回:轉換成功為 0,轉換失敗為 -1。

2.2 函數說明

  • 當需要轉換的進制數大于 35 即超過最大進制限度(0 ~ 9、a ~ z)時,或小于 2 即最小進制限度時,或把負數轉換為非十進制的負數時,應傳回 -1 表示轉換失敗。

2.3 函數實作

int itoa(int num, char* str, int radix)
{
    // 超出轉換進制限度
    if ((radix > 35) || (radix < 2) || (num < 0 && radix != 10))
    {
        return -1;
    }
    
    // 當數值為 0 時,轉換任何進制都為 0,直接進行指派傳回即可
    if (num == 0)
    {
        str[0] == '0';
        str[1] == '\0';
        return 0;
    }
    
    // 把轉換結果倒置存放在記憶體中
	char* p = str;
    int src = num;
    num = src < 0 ? num * (-1) : num;
	while (num != 0)
	{
        if (num % radix < 10)
        {
            *p = num % radix + '0';
        }
        else
        {
            *p = num % radix - 10 + 'a';
        }

		num = num / radix ;
		p++;
	}
    
    if (src < 0)
    {
        *p = '-';
        p++;
    }

    // 添加結尾字元
	*p = '\0';
    
    // 字元串倒置
	for (char* left = str, *right = p - 1; left < right; left++, right--)
	{
		char tmp = *left;
		*left = *right;
		*right = tmp;
	}

	return 0;
}
           

更多造輪子系列博文