128位字符串到数组使用boost :: spirit :: * [英] 128 bit string to array using boost::spirit::*

查看:452
本文介绍了128位字符串到数组使用boost :: spirit :: *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从boost :: spirit :: *开始。我试图解析一个128位字符串到一个简单的c数组与相应的大小。我创建了一个简短的测试,这样做的工作:

I am currently starting with boost::spirit::*. I try to parse a 128 bit string into a simple c array with corresponding size. I created a short test which does the job:

    boost::spirit::qi::int_parser< boost::uint8_t, 16, 2, 2 > uint8_hex;
    std::string src( "00112233445566778899aabbccddeeff" );
    boost::uint8_t dst[ 16 ];

    bool r;
    for( std::size_t i = 0; i < 16; ++i )
    {
        r = boost::spirit::qi::parse( src.begin( ) + 2 * i, src.begin( ) + 2 * i + 2, uint8_hex, dst[ i ] );
    }



我感觉这不是最聪明的方式任何想法如何定义规则,以便避免循环?

I have the feeling that this is not the smartest way to do it :) Any ideas how to define a rule so I can avoid the loop ?

更新:

在此期间,我想出了以下的代码,这工作非常好:

In the meantime I figured out the following code which does the job very well:

    using namespace boost::spirit;
    using namespace boost::phoenix;

    qi::int_parser< boost::uint8_t, 16, 2, 2 > uint8_hex;

    std::string src( "00112233445566778899aabbccddeeff" );

    boost::uint8_t dst[ 16 ];
    std::size_t i = 0;

    bool r = qi::parse( src.begin( ),
                        src.end( ),
                        qi::repeat( 16 )[ uint8_hex[ ref( dst )[ ref( i )++ ] = qi::_1 ] ] );


推荐答案

不是真正的问题,如果你真的想只是为了解析一个128位整数的十六进制表示,可以使用Boost Multiprecision中定义的 uint128_t 来移植:

Not literally staying with the question, if you really wanted just to parse the hexadecimal representation of a 128 bit integer, you can do so portably by using uint128_t defined in Boost Multiprecision:

qi::int_parser<uint128_t, 16, 16, 16> uint128_hex;

uint128_t parsed;
bool r = qi::parse(f, l, uint128_hex, parsed);

这将是最快的方式,特别是在指令集中支持128位类型的平台上。

This is bound to be the quickest way especially on platforms where 128bit types are supported in the instruction set.

Live On Coliru

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/spirit/include/qi.hpp>

namespace qi  = boost::spirit::qi;

int main() {
    using boost::multiprecision::uint128_t;
    using It = std::string::const_iterator;
    qi::int_parser<uint128_t, 16, 16, 16> uint128_hex;

    std::string const src("00112233445566778899aabbccddeeff");
    auto f(src.begin()), l(src.end());

    uint128_t parsed;
    bool r = qi::parse(f, l, uint128_hex, parsed);

    if (r) std::cout << "Parse succeeded: " << std::hex << std::showbase << parsed << "\n";
    else   std::cout << "Parse failed at '" << std::string(f,l) << "'\n";

}

这篇关于128位字符串到数组使用boost :: spirit :: *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆