首页 > 编程 > PHP > 正文

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

2019-11-21 20:58:05
字体:
来源:转载
供稿:网友

介绍

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;}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如有疑问大家可以留言交流,谢谢大家对武林网的支持。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表