整型(php中字符串如何转换整型)

发布时间:2025-12-11 02:26:38 浏览次数:1

php字符串转换整型的方法:1、通过“intval($num);”方法将字符串类型的数字转成整型的数字;2、利用ascii码的方式将字符串转成整型。

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类型,下面具体看代码实现.

functionconvertInt($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>/*Convertastringintoalonglong.Returns1ifthestringcouldbeparsed*intoa(non-overflowing)longlong,0otherwise.Thevaluewillbesetto*theparsedvaluewhenappropriate.*/intstring2ll(constchar*s,size_tslen,longlong*value){constchar*p=s;size_tplen=0;intnegative=0;unsignedlonglongv;if(plen==slen)return0;/*Specialcase:firstandonlydigitis0.*/if(slen==1&&p[0]=='0'){if(value!=NULL)*value=0;return1;}if(p[0]=='-'){negative=1;p++;plen++;/*Abortononlyanegativesign.*/if(plen==slen)return0;}/*Firstdigitshouldbe1-9,otherwisethestringshouldjustbe0.*/if(p[0]>='1'&&p[0]<='9'){v=p[0]-'0';p++;plen++;}elseif(p[0]=='0'&&slen==1){*value=0;return1;}else{return0;}while(plen<slen&&p[0]>='0'&&p[0]<='9'){if(v>(ULLONG_MAX/10))/*Overflow.*/return0;v*=10;if(v>(ULLONG_MAX-(p[0]-'0')))/*Overflow.*/return0;v+=p[0]-'0';p++;plen++;}/*Returnifnotallbyteswereused.*/if(plen<slen)return0;if(negative){if(v>((unsignedlonglong)(-(LLONG_MIN+1))+1))/*Overflow.*/return0;if(value!=NULL)*value=-v;}else{if(v>LLONG_MAX)/*Overflow.*/return0;if(value!=NULL)*value=v;}return1;}//--------执行---------intmain(){longlongnum;string2ll("345432123",strlen("345432123"),&num);printf("%d\n",num);//输出345432123retunr0;}
整型
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477