我目前开始使用 boost::spirit::*。我尝试将 128 位字符串解析为具有相应大小的简单 c 数组。我创建了一个简短的测试来完成这项工作:
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 ] );
}
我觉得这不是最明智的做法 :) 有什么想法可以定义规则以避免循环吗?
更新:
与此同时,我想出了以下代码,它可以很好地完成工作:
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
来轻松地做到这一点:
qi::int_parser<uint128_t, 16, 16, 16> uint128_hex;
uint128_t parsed;
bool r = qi::parse(f, l, uint128_hex, parsed);
这肯定是最快的方法,尤其是在指令集支持 128 位类型的平台上。
#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";
}
关于c++ - 128 位字符串数组使用 boost::spirit::*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28073725/