简单的十进制数字与二,八,十六进制互转

算法原理不多说了,网上很多,二,八,十六,道理都一样,直接上代码

/**
 * 十进制转各进制
 *
 * @param int $number
 * @param int|string $format
 */
function int10tomixed2_8_16($number,$format){
	// 转换所需数组
	$spc = array(0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f');
	$t = "";
	if($number===0)continue;
	/*
	 * 基于算法
	 * 例:$number=521, $format=2 
	 * 521%2 ==0, 在数组中寻找对应值,接着取$number除以$format后的最小整数(521/2=260.5取260),继续循环
	 */
	while ($number>0) {
		$t = $spc[$number%$format].$t;
		$number = floor($number/$format);
	}
    echo $t."<br/>";
}

/**
 * 各进制转十进制
 *
 * @param mixed|string|int $numstr
 * @param int|string $sformat
 */
function mixed2_8_16toint10($numstr,$sformat){
	// 转换所需数组
	$spc = array(0,1,2,3,4,5,6,7,8,9,'a'=>10,'b'=>11,'c'=>12,'d'=>13,'e'=>14,'f'=>15);
	// 反转字符
	$numstr = strrev($numstr);
	for($i=0;$i<strlen($numstr);$i++){
		// 例:5bb(16),b*16^0+b*16^1+5*16^2
		$num += ($spc[$numstr{$i}])*pow($sformat,$i);
	}
	echo $num."<br/>";
}


int10tomixed2_8_16(302,2);
int10tomixed2_8_16(302,8);
int10tomixed2_8_16(302,16);
mixed2_8_16toint10("100101110",2);
mixed2_8_16toint10("456",8);
mixed2_8_16toint10("5bb",16);//jkj


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值