您好,欢迎访问一九零五行业门户网

PHP实现不使用内置函数实现字符串转整型方法

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; }
相关推荐:
sql convert() 字符串转整型 日期 字符型
以上就是php实现不使用内置函数实现字符串转整型方法的详细内容。
其它类似信息

推荐信息