简体   繁体   English

如何将任意基数的字符串版本转换为整数?

[英]How do I convert a string version of a number in an arbitrary base to an integer?

how to convert string to integer?? 如何将字符串转换为整数?

for ex: 例如:

  • "5328764",to int base 10 “ 5328764”,以int为基础的10
  • "AB3F3A", to int base 16 “ AB3F3A”,以int为基数16

any code will be helpfull 任何代码都会有所帮助

Assuming arbitrary base (not 16, 10, 8, 2): 假设任意基数(不是16、10、8、2):

In C (C++), use strtol 在C(C ++)中,使用strtol

return strtol("AB3F3A", NULL, 16);

In Javascript, use parseInt . 在Javascript中,使用parseInt

return parseInt("AB3F3A", 16);

In Python, use int(string, base) . 在Python中,使用int(string, base)

return int("AB3F3A", 16)

In Java, use Integer.parseInt (thanks Michael.) 在Java中,使用Integer.parseInt (感谢Michael。)

return Integer.parseInt("AB3F3A", 16);

In PHP, use base_convert . 在PHP中,使用base_convert

return intval(base_convert('AB3F3A', 16, 10));

In Ruby, use to_i 在Ruby中,使用to_i

"AB3F3A".to_i(16)

In C#, write one yourself. 在C#中,自己编写一个。

9999 is really 9000 + 900 + 90 + 9 So, start at the right hand side of the string, and pick off the numbers one at a time. 9999实际上是9000 + 900 + 90 + 9因此,从字符串的右侧开始,然后一次选取一个数字。 Each character number has an ASCII code, which can be translated to the number, and multiplied by the appropriate amount. 每个字符号都有一个ASCII码,可以将其转换为数字并乘以适当的数量。

在C#中,我认为它是:Convert.ToInt64(value,base)并且基数必须为2、8、10或16

Two functions in java, in both directions: "code" parameter represent the numerical system: "01" for base 2, "0123456789" for base 10, "0123456789abcdef" for hexdecimal and so on... Java中的两个函数,双向:“ code”参数代表数值系统:“ 01”表示基数2,“ 0123456789”表示基数10,“ 0123456789abcdef”表示十六进制,依此类推...

public String convert(long num, String code) {
    final int base = code.length();
    String text = "";
    while (num > 0) {
        text = code.charAt((int) (num%base)) + text;
        num /= base;
    }
    return text;
}

public long toLong(String text, String code) {
    final long base = code.length();
    long num = 0;
    long pow = 1;
    int len = text.length();
    for(int i = 0; i < len; i++) {
        num += code.indexOf(text.charAt(len - i - 1)) * pow;
        pow *= base;
    }
    return num;
}

println(convert(9223372036854775807L,"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
println(convert(9223372036854775807L,"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@=-+*/^%$#&()!?.,:;[]"));
println(toLong("Ns8T$87=uh","0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@=-+*/^%$#&()!?.,:;[]"));```

in your example: 在您的示例中:

toLong("5328764", "0123456789") = 5328764
toLong("AB3F3A", "0123456789ABCDEF") = 11222842

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM