我用dlang语言实现了一个进制转换的函数代码如下:import stdstdio;private char intToCharint num if num = 0 && num = 9 return castcharnum + 0; else return castcharnum - 10 + a; private int c
。下面是改进后的代码:
import std.stdio;
private char intToChar(int num) { if (num >= 0 && num <= 9) { return cast(char)(num + '0'); } else if (num >= 10 && num <= 35) { return cast(char)(num - 10 + 'a'); } else { throw new Exception("Invalid number"); } }
private int charToInt(char ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } else if (ch >= 'a' && ch <= 'z') { return ch - 'a' + 10; } else if (ch >= 'A' && ch <= 'Z') { return ch - 'A' + 10; } else { throw new Exception("Invalid character"); } }
string base_convert(string num, ubyte from_base=10, ubyte to_base=2) { // 将 num 转换为十进制 int decimal = 0; foreach (ch; num) { int digit; try { digit = charToInt(ch); } catch (Exception e) { continue; } 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("j37334", 16, 2)); //抛出异常 writeln(base_convert("FF", 16, 10)); //255 writeln(base_convert("101010", 2, 16)); //2a
原文地址: https://www.cveoy.top/t/topic/fG0T 著作权归作者所有。请勿转载和采集!