未知位大小的模板化整数
templating integer of unknown bitsize
鉴于我不知道字符串会有多大,我将如何将二进制/十六进制字符串转换为整数?
我想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;
}
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 继承期间显示未知行为的子类
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 比较两个整数在C++中与未知 int 类型的相等性
- C++ 读取未知数量的整数到 cin 并输出总和
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 保存未知数量的整数,而不会花费太多时间/内存
- 将未知大小的整数转换为其无符号形式的最短/最干净方法
- 如何将.txt文件中的未知数字整数保存到数组中
- 如何找到未知整数类型的最大值
- dev C++ 读取固定数量的整数行,每行中整数数量未知
- 输入一个未知的整数流,并对其进行整数运算
- 未知位大小的模板化整数
- C++矢量错误 C2036:"整数 (*)[]":未知大小