int转字符串实现方法
【摘要】 抖音的分享链接一般为: https://v.douyin.com/JGoSFt2/那么后面那串 JGoSFt2 是什么呢?其实后面那串为分享id转字符串,原始数据可能为 :1091566355946 ,通过特定算法转换为了更短的字符串实现代码为:<?phpnamespace EasySwoole\Utility;class IntStr{ public const intMax =...
抖音的分享链接一般为: https://v.douyin.com/JGoSFt2/
那么后面那串 JGoSFt2 是什么呢?
其实后面那串为分享id转字符串,原始数据可能为 :1091566355946 ,通过特定算法转换为了更短的字符串
实现代码为:
<?php
namespace EasySwoole\Utility;
class IntStr
{
public const intMax = 9223372036854775668;
private const alphabet = [
'A','a','B','b','C','c','D','d','E', 'e',
'F','f','G','g','H','h','I','i','J','j',
'K','k','L','l','M','m','N','n','O','o',
'P','p','Q','q','R','r','S','s','T','t',
'U','u','V','v','W','w','X','x', 'Y','y',
'Z','z','0','1','2','3','4','5','6','7','8','9'
];
public static function toAlpha($number):string
{
if($number < 0 && $number > self::intMax){
throw new \InvalidArgumentException('number error');
}
$alpha = '';
if($number <= 61){
return self::alphabet[$number];
} elseif($number > 61){
$dividend = ($number + 1);
while ($dividend > 0){
$modulo = ($dividend - 1) % 62;
if($modulo < 0){
$modulo = 62+$modulo;
}
$alpha = self::alphabet[$modulo] . $alpha;
$dividend = floor((($dividend - $modulo) / 62));
}
}
return $alpha;
}
public static function toNum($string):int
{
$alpha_flip = array_flip(self::alphabet);
$return_value = -1;
$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
$return_value +=
($alpha_flip[$string[$i]] + 1) * pow(62, ($length - $i - 1));
}
return $return_value;
}
}
复制
运行:
<?php
include "./vendor/autoload.php";
var_dump(\EasySwoole\Utility\IntStr::toNum('JGoSFt2'));
var_dump(\EasySwoole\Utility\IntStr::toAlpha(100000000000000));
复制
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)