繁体   English   中英

在C ++中将一串字节拆分为BYTES的向量

[英]Splitting a string of bytes to vector of BYTES in C++

我有一个字节字符串,如下所示:

"1,3,8,b,e,ff,10"

如何将此字符串拆分为包含以下值的BYTE的std :: vector:

[0x01,0x03,0x08,0x0b,0x0e,0xff,0x10]

我正在尝试使用','作为分隔符来拆分字符串,但是我在使用它时遇到了一些麻烦。 有人可以帮助我解决这个问题吗?

所以我试过这个:

    std::istringstream iss("1 3 8 b e ff 10");
    BYTE num = 0;
    while(iss >> num || !iss.eof()) 
    {
        if(iss.fail()) 
        {
            iss.clear();
            std::string dummy;
            iss >> dummy;
            continue;
        }
        dataValues.push_back(num);
    }

但是这会将ascii字节值推送到向量中:

49 //1
51 //3
56 //8
98 //b
101 //e
102 //f
102 //f
49 //1
48 //0

我试图填充向量:

 0x01
 0x03
 0x08
 0x0b
 0x0e
 0xff
 0x10

您刚刚错过了根据我的评论中的链接答案调整您的用例中出现的一些小问题:

    std::istringstream iss("1,3,8,b,e,ff,10");
    std::vector<BYTE> dataValues;

    unsigned int num = 0; // read an unsigned int in 1st place
                          // BYTE is just a typedef for unsigned char
    while(iss >> std::hex >> num || !iss.eof()) {
        if(iss.fail()) {
            iss.clear();
            char dummy;
            iss >> dummy; // use char as dummy if no whitespaces 
                          // may occur as delimiters
            continue;
        }
        if(num <= 0xff) {
            dataValues.push_back(static_cast<BYTE>(num));
        }
        else {
            // Error single byte value expected
        }
    }

您可以在ideone上看到完整工作的示例。

一个工作示例代码(使用C ++ 11在GCC 4.9.0中测试):

save.txt文件包含: 1,3,8,b,e,ff,10作为第一个唯一行。

输出:

1
3
8
b
e
ff
10

这个想法是:

  • 使用std :: getline逐行读取。
  • 使用boost :: split根据分隔符拆分线。
  • 用户std :: stringstream将十六进制字符串转换为unsigned char。

码:

#include <fstream>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/lexical_cast.hpp>

int main(int argc, char* argv[]) {
    std::ifstream ifs("e:\\save.txt");

    std::string line;
    std::vector<std::string> tokens;
    std::getline(ifs, line);
    boost::split(tokens, line, boost::is_any_of(","));

    std::vector<unsigned char> values;
    for (const auto& t : tokens) {
        unsigned int x;
        std::stringstream ss;
        ss << std::hex << t;
        ss >> x;

        values.push_back(x);
    }

    for (auto v : values) {
        std::cout << std::hex << (unsigned long)v << std::endl;
    }

    return 0;
}

只是为了演示另一种可能更快的做事方式,考虑将所有内容读入数组并使用自定义迭代器进行转换。

class ToHexIterator : public std::iterator<std::input_iterator_tag, int>{
    char* it_;
    char* end_;
    int current_;
    bool isHex(const char c){
        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
    }
    char toUpperCase(const char c){
        if (c >= 'a' && c <= 'f'){
            return (c - 'a') + 'A';
        }
        return c;
    }
    int toNibble(const char c){
        auto x = toUpperCase(c);
        if (x >= '0' && x <= '9'){
            return x - '0';
        }
        else {
            return (x - 'A') + 10;
        }
    }
public:
    ToHexIterator() :it_{ nullptr }, end_{ nullptr }, current_{}{}                  //default constructed means end iterator
    ToHexIterator(char* begin, char* end) :it_{ begin }, end_{ end }, current_{}{
        while (!isHex(*it_) && it_ != end_){ ++it_; };  //make sure we are pointing to valid stuff
        ++(*this);
    }
    bool operator==(const ToHexIterator &other){
        return it_ == nullptr && end_ == nullptr && other.it_ == nullptr && other.end_ == nullptr;
    }
    bool operator!=(const ToHexIterator &other){
        return !(*this == other);
    }
    int operator*(){
        return current_;
    }
    ToHexIterator & operator++(){
        current_ = 0;
        if (it_ != end_) {
            while (isHex(*it_) && it_ != end_){
                current_ <<= 4;
                current_ += toNibble(*it_);
                ++it_;
            };
            while (!isHex(*it_) && it_ != end_){ ++it_; };
        }
        else {
            it_ = nullptr;
            end_ = nullptr;
        }
        return *this;
    }
    ToHexIterator operator++(int){
        ToHexIterator temp(*this);
        ++(*this);
        return temp;
    }
};

基本用例如下:

char in[] = "1,3,8,b,e,ff,10,--";
std::vector<int> v;
std::copy(ToHexIterator{ std::begin(in), std::end(in) }, ToHexIterator{}, std::back_inserter(v));

请注意,使用查找表执行ascii到hex半字节转换可能会更快。

速度可能非常依赖于编译器优化和平台,但是因为某些istringstream函数是作为虚函数或指向函数的指针实现的(取决于标准库实现),优化器会遇到问题。 在我的代码中没有victuals或函数指针,唯一的循环是在优化器用于处理的std :: copy实现中。 它通常也更快地循环,直到两个地址相等而不是循环,直到一些改变指针指向的东西等于某事。 在一天结束时,我所有的猜测和伏都教,但在我的机器上的MSVC13上快了大约10倍。 这是一个关于GCC的实际示例http://ideone.com/nuwu15 ,根据运行情况介于10x和3x之间,取决于首先进行的测试(可能是因为某些缓存效果)。

总而言之,毫无疑问会有更多的优化空间等等。任何在这个抽象层面上说“我的总是更快”的人都在卖蛇油。

更新:使用编译时生成的查找表进一步提高速度: http//ideone.com/ady8GY (请注意,我增加了输入字符串的大小以降低噪音,因此这与上面的示例无法直接比较)

暂无
暂无

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

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