PHP實現不使用內建函數實現字串轉整型方法

來源:互聯網
上載者:User
php字串類型的數字如果想轉成整型的數字,一般我們都是採用系統內建的API去做轉換,但如果規定就不讓我們去用系統內建的API轉換,而是讓自己去實現一個函數轉換該怎麼辦?這裡我們看下如何去實現。

系統內建 API 方式

$num = '345432123'; //(一)$num = (int)$num;//輸出://int(345432123)//(二)$num = intval($num);//輸出://int(345432123)

採用 ASCII 碼方式

下面我們利用 ascii 碼的方式去做轉換,因為每個字元都對應一個 ascii 碼,當對這個字元做加減乘除的時候,實際上就是對 ascii 碼做加減乘除操作,也就是整型操作,最終會返回一個整型數字.


-圖片轉自網路-

通過可以看到字元 '0' ~ '9' 的 ascii 碼是 48~57 我們在轉換的時候就是用每一個字元減去 '0' 例如: '1' - '0' = 1、'2' - '0' = 2 傳回值就是一個Int類型,下面具體看代碼實現.

function convertInt($strInt = ''){  $len = strlen($strInt);  $int = 0; for($i=0;$i<$len;$i++){  $int *= 10;     $num = $strInt{$i} - '0';     $int += $num;   } return $int;  } $num = '345432123';  var_dump(convertInt($num)); //輸出: int(345432123)

在 Redis 裡面也有提供一個字串轉整型的函數,也是通過ascii碼方式去做的,實現的比較完善嚴謹,具體可以參考下

string2ll 函數

#include <stdio.h>#include <limits.h>#include <string.h>/* Convert a string into a long long. Returns 1 if the string could be parsed * into a (non-overflowing) long long, 0 otherwise. The value will be set to * the parsed value when appropriate. */int string2ll(const char *s, size_t slen, long long *value) { const char *p = s; size_t plen = 0; int negative = 0; unsigned long long v; if (plen == slen)  return 0; /* Special case: first and only digit is 0. */ if (slen == 1 && p[0] == '0') {  if (value != NULL) *value = 0;  return 1; } if (p[0] == '-') {  negative = 1;  p++; plen++;  /* Abort on only a negative sign. */  if (plen == slen)   return 0; } /* First digit should be 1-9, otherwise the string should just be 0. */ if (p[0] >= '1' && p[0] <= '9') {  v = p[0]-'0';  p++; plen++; } else if (p[0] == '0' && slen == 1) {  *value = 0;  return 1; } else {  return 0; } while (plen < slen && p[0] >= '0' && p[0] <= '9') {  if (v > (ULLONG_MAX / 10)) /* Overflow. */   return 0;  v *= 10;  if (v > (ULLONG_MAX - (p[0]-'0'))) /* Overflow. */   return 0;  v += p[0]-'0';  p++; plen++; } /* Return if not all bytes were used. */ if (plen < slen)  return 0; if (negative) {  if (v > ((unsigned long long)(-(LLONG_MIN+1))+1)) /* Overflow. */   return 0;  if (value != NULL) *value = -v; } else {  if (v > LLONG_MAX) /* Overflow. */   return 0;  if (value != NULL) *value = v; } return 1;}//-------- 執行 ---------int main(){ long long num; string2ll("345432123",strlen("345432123"),&num); printf("%d\n",num); //輸出 345432123 retunr 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.