1. 程式人生 > >自己實現C語言atoi函式和執行緒安全版的itoa函式

自己實現C語言atoi函式和執行緒安全版的itoa函式

C語言atoi函式是用來將字串轉化為int型整數的,itoa功能相反。下面是我自己實現的這兩個函式,均為執行緒安全的。程式碼如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <iostream>
#include <cmath>

using namespace std;

//將一個字元轉化為數字
int chartoi(const char cp)
{
    if ('0' <= cp&&'9'
>= cp) { //字元數字在記憶體中的值都是通過自身加上0x30得到的 return cp - 0x30; } else { printf_s("error input.%s, %d", __FILE__, __LINE__); return -1; } } //內建型別,直接傳值 int myatoi(const char* ptr) { const char* tmptr = NULL; int neg = 0; int len = 0, temp_len = 0; int
value = 0; len = strlen(ptr); temp_len = len; if ('-' == ptr[0]) { tmptr = ptr + 1; --temp_len; } else { neg = 1; tmptr = ptr; } while (temp_len > 0) { value += chartoi(*tmptr) * pow(10, (temp_len - 1)); temp_len--; tmptr++; } if
(neg == 0) return 0 - value; else return value; } //執行緒安全版本1(由使用者自己制定一塊記憶體並將地址傳入, //此記憶體可以為棧上的也可以是堆上的) int myitoa(int num, char* ptr) { if (NULL == ptr) return 1; int neg = 0, i = 0; int temp = num; char buf[128]; memset(buf, 0, sizeof(buf)); if (num > 0) neg = 1; else temp = 0 - num; while (temp > 0) { buf[i++] = temp % 10 + 0x30; temp /= 10; } if (neg == 0) { buf[i] = '-'; } reverse(buf, buf+strlen(buf)); sprintf_s(ptr, strlen(buf)+1, buf); return 0; } //執行緒安全版本2(直接通過函式在堆上開闢記憶體並傳出, //注意使用完需要free堆上的記憶體) char* myitoa(int num) { int neg = 0, i = 0; int temp = num; char* buf = (char*)malloc(128); if (NULL == buf) return NULL; if (num > 0) neg = 1; else temp = 0 - num; while (temp > 0) { buf[i++] = temp % 10 + 0x30; temp /= 10; } if (neg == 0) { buf[i++] = '-'; buf[i] = '\0'; } else { buf[i] = '\0'; } reverse(buf, buf + strlen(buf)); return buf; } //執行緒安全版本3(通過傳入二級指標在函式內部向堆上申請記憶體,也可以通過 //傳入指標的引用實現,但是需注意使用完了之後需要free堆上的記憶體) int myitoa(int num, char** ptr) { int neg = 0, i = 0; int temp = num; *ptr = (char*)malloc(128); if (NULL == ptr) { return 1; } if (num > 0) neg = 1; else temp = 0 - num; while (temp > 0) { (*ptr)[i++] = temp % 10 + 0x30; temp /= 10; } if (neg == 0) { (*ptr)[i++] = '-'; (*ptr)[i] = '\0'; } else { (*ptr)[i] = '\0'; } reverse(*ptr, *ptr + strlen(*ptr)); return 0; } int main() { char *p = "-123"; int a = -123; char* buf; //myitoa(a, &buf); printf("%d\n", myatoi(p)); //printf("%s\n", buf); //free(buf); return 0; }