简体   繁体   English

在 C++ 中将字符串转换为数字

[英]Converting string to number in C++

I intend to convert a string into an array of numbers.我打算将一个字符串转换为一个数字数组。 For instance the below code works well:例如下面的代码运行良好:

// A program to demonstrate the use of stringstream 
#include <iostream> 
#include <sstream> 
using namespace std; 

int main() 
{ 
    string s = "12345"; 

    // object from the class stringstream 
    stringstream geek(s); 

    // The object has the value 12345 and stream 
    // it to the integer x 
    int x = 0; 
    geek >> x; 

    // Now the variable x holds the value 12345 
    cout << "Value of x : " << x; 

    return 0; 
}

How do I do it for a very big string.我该如何处理一个非常大的字符串。 For example, string s = "77980989656B0F59468581875D719A5C5D66D0A9AB0DFDDF647414FD5F33DBCBE"例如,字符串 s = "77980989656B0F59468581875D719A5C5D66D0A9AB0DFDDF647414FD5F33DBCBE"

I need to store this into an array of chars, arr[32].我需要将它存储到一个字符数组 arr[32] 中。 arr[0] should have 0x77, arr[1] should have 0x98 and so on. arr[0] 应该有 0x77,arr[1] 应该有 0x98 等等。 Considering string s is of 64 bytes.考虑到字符串 s 是 64 字节。 my array would be 32 bytes long.我的数组长 32 个字节。

Can someone help with this?有人可以帮忙吗?

You can try to split the input string into substrings where each substring has 2 characters length.您可以尝试将输入字符串拆分为子字符串,其中每个 substring 的长度为 2 个字符。 Then convert the hexadecimal substring using std::stoi() function into integer and store each converted result to an std::vector container:然后使用 std::stoi() function 将十六进制 substring 转换为 integer 并将每个转换结果存储到 std::vector 容器:

#include <vector>
#include <iostream>


std::vector<int> convert(const std::string& hex_str) {

    std::vector<int> output;
    std::string::const_iterator last = hex_str.end();
    std::string::const_iterator itr = hex_str.cbegin();

    if (hex_str.size() % 2) {
        last--;
    }

    while(itr != last) {

        std::string sub_hex_str;
        std::copy(itr,itr+2,std::back_inserter(sub_hex_str));
        try {
            output.push_back(std::stoi(sub_hex_str,0,16));
        }catch(const std::exception& e) {
            std::cerr << sub_hex_str << " : " << e.what() << std::endl;
        }

        itr += 2;       
    }

    return output;
}

int main()
{
    std::string a = "77980989656B0F59468581875D719A5C5D66D0A9AB0DFDDF647414FD5F33DBCBE";

    const auto output = convert(a);

    for(const auto& a: output) {
        std::cout << a << std::endl;
    }
}

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

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