繁体   English   中英

用小端序提升 asio

[英]boost asio with little endian

我正在集成一个需要小字节序长度的库。 它使用小端格式,然后是自定义序列化对象。 如何将 4 字节 char 转换为 int? little endian 告诉我要读取的序列化对象的大小。

所以如果我收到 "\x00\x00\x00H\x00" 我希望能够得到十进制值。

我的图书馆看起来像

char buffer_size[size_desc]
m_socket->receive(boost::asio::buffer(buffer, size_desc));
int  converted_int = some_function(buffer); <-- not sure what to do here
char buffer_obj[converted_int];
m_socket->receive(boost::asio::buffer(buffer, size_desc));

对于一个简单的解决方案,你可以做几个技巧,Reverse with a cast:

// #include <stdafx.h>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <algorithm>
#include <string>

int main()
{
    char buff[4] = {3,2,1,0};

    std::cout <<  (*reinterpret_cast<int*>(&buff[0])) << "\n";

    std::reverse(buff, buff+4);

    std::cout <<  (*reinterpret_cast<int*>(&buff[0]));

    return 0;

};

Boost 还附带了一个字节顺序库: https ://www.boost.org/doc/libs/1_74_0/libs/endian/doc/html/endian.html#buffers

您可以使用内置类型,例如:

  • big_int32_t
  • little_int16_t

暂无
暂无

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

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