I am trying to convert this Python code into PHP but I got stuck on handling bytes data. Can someone help me fix this PHP code so I can get the same result as Python which is 2734?
PYTHON VERSION
indexes = [8, 13, 23, 13, 37, 23, 31, 11, 8, 37, 23, 27, 12, 9, 21, 20, 6, 8, 12, 16, 12, 17, 35, 37, 35, 28, 13, 35, 9, 31, 2, 25]
sha_1_sign = 'cf493b66e356e588c545df7dda24ed4d404f1c90'
sha_1_b = sha_1_sign.encode("ascii")
checksum = sum([sha_1_b[number] for number in indexes])
print(checksum)
#result 2734
PHP VERSION
$indexes = [8, 13, 23, 13, 37, 23, 31, 11, 8, 37, 23, 27, 12, 9, 21, 20, 6, 8, 12, 16, 12, 17, 35, 37, 35, 28, 13, 35, 9, 31, 2, 25];
$sha_1_sign = 'cf493b66e356e588c545df7dda24ed4d404f1c90';
$sha_1_b = hex2bin($sha_1_sign);
$checksum = 0;
foreach ($indexes as $number) {
if (isset($sha_1_b[$number])) {
$checksum += ord($sha_1_b[$number]);
}
}
echo $checksum;
#result 2047
>Solution :
The python code treats each individual character as a separate entity, and takes the ASCII value of it. The PHP code converts the hex string to its binary representation, and then tries to refer to it as an array. I’d change it by splitting into an array of single characters first, then mapping each of those characters to their ASCII values. Then just use the number from $indexes as the index of the value to add:
$indexes = [...];
$sha_1_sign = 'cf493b66e356e588c545df7dda24ed4d404f1c90';
$sha_1_b = array_map(fn($a) => ord($a), str_split($sha_1_sign));
$checksum = 0;
foreach ($indexes as $number) {
$checksum += $sha_1_b[$number];
}
echo $checksum;
Or you can one-line it, by mapping each value in $indexes to its associated index in $sha_1_b, and then summing the resulting mapped array:
$indexes = [...];
$sha_1_sign = 'cf493b66e356e588c545df7dda24ed4d404f1c90';
$sha_1_b = array_map(fn($a) => ord($a), str_split($sha_1_sign));
$checksum = array_sum(array_map(fn($a) => $sha_1_b[$a], $indexes));
echo $checksum;
You might also use PHP’s little-used string-as-array feature, which allows you to refer to a character in a string via the array syntax. I’m not a big fan of this notation though, because it can be confusing for other people to look at your code, who might think the reference is an array when it’s really a string:
$sha_1_sign = 'cf493b66e356e588c545df7dda24ed4d404f1c90';
$checksum = 0;
foreach ($indexes as $number) {
$checksum += ord($sha_1_sign[$number]);
}
echo $checksum;
Or, the super short version:
$indexes = [...];
$sha_1_sign = 'cf493b66e356e588c545df7dda24ed4d404f1c90';
$checksum = array_sum(array_map(fn($a) => ord($sha_1_sign[$a]), $indexes));
echo $checksum;