Last active
December 24, 2015 01:49
-
-
Save adrinavarro/6726189 to your computer and use it in GitHub Desktop.
Requires BC. Convert info_hash from short versions (deprecated) to 40-char length ones.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function convert_base($numberInput, $fromBaseInput, $toBaseInput) { | |
if ($fromBaseInput == $toBaseInput) return $numberInput; | |
$fromBase = str_split($fromBaseInput,1); | |
$toBase = str_split($toBaseInput,1); | |
$number = str_split($numberInput,1); | |
$fromLen = strlen($fromBaseInput); | |
$toLen = strlen($toBaseInput); | |
$numberLen = strlen($numberInput); | |
$retval = ''; | |
if($toBaseInput == '0123456789') { | |
$retval = 0; | |
for($i = 1; $i <= $numberLen; $i++) { | |
$retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase), bcpow($fromLen, $numberLen-$i))); | |
} | |
return $retval; | |
} | |
if($fromBaseInput != '0123456789') { | |
$base10 = convert_base($numberInput, $fromBaseInput, '0123456789'); | |
} else { | |
$base10 = $numberInput; | |
} | |
if ($base10 < strlen($toBaseInput)) { | |
return $toBase[$base10]; | |
} | |
while($base10 != '0') { | |
$retval = $toBase[bcmod($base10,$toLen)].$retval; | |
$base10 = bcdiv($base10,$toLen,0); | |
} | |
return $retval; | |
} | |
function convert_info_hash($input) { | |
$result = convert_base($input, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', '0123456789ABCDEF'); | |
$result = str_pad($result, 40, '0', STR_PAD_LEFT); | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment