[英]convert a long string of characters to uint32_t or uint64_t in c++
I want to convert a string containing alphanumeric characters into either uint32_t or uint64_t.我想将包含字母数字字符的字符串转换为 uint32_t 或 uint64_t。 Tried doing the following.
尝试执行以下操作。 But, I am getting "terminate called after throwing an instance of 'std::out_of_range' " error.
但是,我收到“在抛出 'std::out_of_range' 实例后调用终止”错误。 Also, when the string is smaller in length, for example : string s = "hello", it works, but what if I want to convert a longer string into uint32_t or uint64_t.
此外,当字符串的长度较小时,例如:string s = "hello",它可以工作,但是如果我想将较长的字符串转换为 uint32_t 或 uint64_t 该怎么办。
#include <iostream>
#include <sstream>
#include <iomanip>
std::string string_to_hex(const std::string& in) {
std::stringstream ss;
ss << std::hex << std::setfill('0');
for (size_t i = 0; i < in.size(); ++i) {
ss << std::setw(2) << static_cast<unsigned int>(static_cast<unsigned char>(in[i]));
}
return ss.str();
}
int main() {
std::string s = "hello world, this 123";
std::string hex_str = string_to_hex(s);
uint32_t value = std::stoul(hex_str , nullptr, 16);
cout<<value<<endl;
}
Okay, so according to the comments given, is the following the best way to do it?好的,所以根据给出的评论,以下是最好的方法吗?
int main()
{
std::string s = "hello world, this 123";
std::hash<std::string> hashed_name;
uint32_t value = hashed_name(s);
cout<<value<<endl;
return 0;
}
This, strictly speaking, does what you need:严格来说,这可以满足您的需求:
#include <iostream>
#include <string>
#include <unordered_map>
class Converter
{
public:
static int StringToInt(const std::string& s)
{
auto it = cache.find(s);
if (it != cache.end())
return it->second;
cache[s] = count;
lookup[count++] = s;
}
static std::string IntToString(unsigned i)
{
auto it = lookup.find(i);
if (it != lookup.end())
return it->second;
return "";
}
private:
static inline unsigned count = 0;
static inline std::unordered_map<std::string, int> cache;
static inline std::unordered_map<int, std::string> lookup;
};
int main() {
std::string s = "hello world, this 123";
int value = Converter::StringToInt(s);
std::cout << value << std::endl;
std::string s2 = Converter::IntToString(value);
std::cout << s2 << std::endl;
int value2 = Converter::StringToInt("hello world, this 123");
std::cout << value2 << std::endl;
}
Your issue is that the resultant hex_str
is a MASSIVE number.您的问题是生成的
hex_str
是一个hex_str
的数字。 Specifically: 0x68656c6c6f20776f726c642c207468697320313233
具体:
0x68656c6c6f20776f726c642c207468697320313233
You are converting every character to a two-digit hex value (ie one byte).您正在将每个字符转换为两位十六进制值(即一个字节)。 Strings of size 4 (8 if using 64 bit int) or more is going to result in a number way too large to fit in your resultant
uint32_t
or uint64_t
大小为 4(如果使用 64 位 int 则为 8)或更多的字符串将导致数字太大而无法放入生成的
uint32_t
或uint64_t
See this GDB printout of your program查看您程序的 GDB 打印输出
As Remy mentioned in the comments, look into hash algorithms.正如 Remy 在评论中提到的,研究哈希算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.