gpt4 book ai didi

c++ - 使用 boost::spirit 解析二进制文件时更改属性类型

转载 作者:可可西里 更新时间:2023-11-01 17:52:20 26 4
gpt4 key购买 nike

我已经成功使用了boost::spirit::qi解析由内置解析器组成的流(例如 byte_little_word 等)。但是,我现在需要解析不完全属于这些类别之一的数据。例如,我想将一个 16.16 的定点二进制数转换为一个 double ;例如所以little_word << little_16p16会解析 uint16_t其次是 double (从定点数解析)。

我首先考虑了语义操作,但是(我认为...)它们并不合适,因为它们不会更改与解析器关联的属性类型。我也不知道如何调整 employee struct-parsing example对于这种情况,因为它依赖于 boost::fusion 提供的隐式转换.这种方法在这里行不通,因为我显然无法从 uint32_t 定义隐式转换。至 double不会造成重大问题。

我的倾向是我需要添加非终端来包装内置的二进制原始解析器或从头开始编写终端解析器。即使在查看了 qi_binary.hpp 的来源之后,我也不知道该怎么做。谁能提供一些示例代码和/或指导我开始相关引用资料?

最佳答案

    template < typename Iterator >
struct parser : boost::spirit::qi::grammar < Iterator, double(), boost::spirit::ascii::space_type >
{
struct cast_impl
{
template < typename A >
struct result { typedef double type; };

double operator()(boost::fusion::vector < boost::uint16_t, boost::uint16_t > arg) const
{
// cast here
return 0;
}
};

parser() : parser::base_type(main)
{
pair = boost::spirit::qi::little_word >> '.' >> boost::spirit::qi::little_word;
main = pair[boost::spirit::qi::_val = cast(boost::spirit::qi::_1)];
}

boost::spirit::qi::rule < Iterator, boost::fusion::vector < boost::uint16_t, boost::uint16_t > (), boost::spirit::ascii::space_type > pair;
boost::spirit::qi::rule < Iterator, double(), boost::spirit::ascii::space_type > main;

boost::phoenix::function<cast_impl> cast;
};

int _tmain(int argc, _TCHAR* argv[])
{
typedef std::string container;

container data_ = "\x01\x02.\x01\x02";

container::iterator iterator_ = data_.begin();

double value_;

bool result_ =
boost::spirit::qi::phrase_parse(iterator_, data_.end(),
parser < container::iterator > (),
boost::spirit::ascii::space,
value_);

return 0;
}

关于c++ - 使用 boost::spirit 解析二进制文件时更改属性类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9715244/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com