我正在尝试将以下 C 代码(基本上只是尝试将任意整数值转换为字符池中的字符)转换为 PHP:
#include <cstdint>
#include <cstring>
#include <iostream>
uint8_t GetCharacter(uint32_t value) {
static const char* valid_characters = "0123456789ABCDEFGHIJKLMOPQRSTUVWabcdefghijklmnopqrstuvw";
static const size_t valid_characters_l = strlen(valid_characters);
uint8_t c = valid_characters[value % valid_characters_l];
return valid_characters[(value << c) % valid_characters_l];
}
int main() {
uint32_t array[] = {176, 52, 608, 855};
for (size_t i=0; i < 4; i++) {
uint8_t c = GetCharacter(array[i]);
std::cout << array[i] << ": " << (uint32_t) c << "\n";
}
return 0;
}
哪个产量
176: 109
52: 114
608: 85
855: 65
我已经能够提出的 PHP 代码产生以下结果:
176: 109
52: 114
608: 85
855: 104 // << Here's the problem
我很确定我准确地翻译了它,但我找不到问题。
<?php
function getCharacter($index) {
$chars = "0123456789ABCDEFGHIJKLMOPQRSTUVWabcdefghijklmnopqrstuvw";
$c = ord(substr($chars, $index % strlen($chars)));
return ord(substr($chars, ($index << $c) % strlen($chars)));
}
function main() {
$array = array(176, 52, 608, 855);
foreach ($array as $value) {
echo "$value: " . getCharacter($value) . "\n";
}
}
main();
有人可以指出我解决这个问题的正确方向吗?