未知位大小的模板化整数

templating integer of unknown bitsize

本文关键字:整数 未知      更新时间:2023-10-16

鉴于我不知道字符串会有多大,我将如何将二进制/十六进制字符串转换为整数?

我想atoi/atol做什么,但我不知道要输出什么,因为我不知道值是 32 位还是 64 位。此外,atoi不做十六进制,所以101会变得101而不是0x101==257

我假设我需要使用 template<typename T> ,但是我将如何创建要在函数中输出的变量? T varname可以是任何东西,那么是什么让varname成为一个数字而不是指向某个随机位置的指针呢?

模板是编译时的东西。 不能在运行时选择数据类型。 如果输入值不会超过 64 位类型的范围,则只需使用 64 位类型。

进行转换的一种方法(但绝不是唯一方法)如下:

template <typename T>
T hex_to_int(const std::string &str)
{
    T x;
    std::stringstream(str) >> std::hex >> x;
    return x;
}
std::string str = "DEADBEEF";  // hex string
uint64_t x = hex_to_int<uint64_t>(str);
std::cout << x << std::endl;  // "3735928559"

只需要定义一个bigInt类,然后将你的字符串解析成该类;像这样的类: https://mattmccutchen.net/bigint/

也许是未经测试的:

int  // or int64 or whatever you decide on
hexstr2bin ( char *s ) {  // *s must be upper case
int result = 0;     // same type as the type of the function
  while ( *char ) {
    result <<= 16;
    if ( *char ) <= '9' {
      result += *char & 0xF;
    }
    else {
      result = ( *char & 0xF ) + 9;
    }
  }
  return result;
}