繁体   English   中英

c++中将一长串字符转换为uint32_t或uint64_t

[英]convert a long string of characters to uint32_t or uint64_t in c++

我想将包含字母数字字符的字符串转换为 uint32_t 或 uint64_t。 尝试执行以下操作。 但是,我收到“在抛出 'std::out_of_range' 实例后调用终止”错误。 此外,当字符串的长度较小时,例如: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; 
}

好的,所以根据给出的评论,以下是最好的方法吗?

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;
}

严格来说,这可以满足您的需求:

#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;

}

您的问题是生成的hex_str是一个hex_str的数字。 具体: 0x68656c6c6f20776f726c642c207468697320313233

您正在将每个字符转换为两位十六进制值(即一个字节)。 大小为 4(如果使用 64 位 int 则为 8)或更多的字符串将导致数字太大而无法放入生成的uint32_tuint64_t

查看您程序的 GDB 打印输出

正如 Remy 在评论中提到的,研究哈希算法。

暂无
暂无

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

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