簡體   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