用dlang语言实现php的base_convert函数该函数说明如下:base_convertPHP 4 PHP 5 PHP 7 PHP 8base_convert — 在任意进制之间转换数字说明 ¶base_convertstring $num int $from_base int $to_base string返回字符串包含 num 以 to_base 进制的表示。num 本身的进制由 fr
import std.stdio;
char intToChar(int num) { if (num >= 0 && num <= 9) { return cast(char)(num + '0'); } else { return cast(char)(num - 10 + 'a'); } }
int charToInt(char ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } else { return ch - 'a' + 10; } }
string base_convert(string num, int from_base, int to_base) { // 将 num 转换为十进制 int decimal = 0; foreach (ch; num) { int digit = charToInt(ch); if (digit >= from_base) { // 忽略无效字符 continue; } decimal = decimal * from_base + digit; } // 将十进制转换为 to_base 进制 string result = ""; while (decimal > 0) { int remainder = decimal % to_base; char digit = intToChar(remainder); result = digit ~ result; decimal /= to_base; } return result; }
void main() { // 示例 writeln(base_convert("a37334", 16, 2)); // 输出 101000110111001100110100
原文地址: https://www.cveoy.top/t/topic/fG0b 著作权归作者所有。请勿转载和采集!