templating integer of unknown bitsize
How would I convert a binary/hexadecimal string into an integer, given that I don't know how large the string will be?
I want to what atoi
/atol
do, but I don't know what to开发者_运维问答 output because I don't know if the value will be 32 bits or 64 bits. Also, atoi
doesn't do hexadecimal, so 101
will become 101
rather than 0x101==257
.
I assume I need to use template<typename T>
, but how would I create the variable to output in the function? T varname
could be anything, so what makes varname
a number rather than a pointer pointing to some random place?
Templates are a compile-time thing. You cannot choose a data-type at run-time. If your input values won't exceed the range of a 64-bit type, then simply use a 64-bit type.
One way (but by no means the only way) to do the conversion is as follows:
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"
you just need to define a bigInt class and then parse your string into that class; somthing like this class : https://mattmccutchen.net/bigint/
Maybe something like untested this:
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;
}
精彩评论