简体   繁体   中英

boost asio with little endian

I am integrating a library that requires little endian for length. It's formatted with little endian and then a custom serialized object. How do I convert 4 byte char into a int? The little endian tells me the size of the serialized object to read.

so if I receive "\x00\x00\x00H\x00" I would like to be able to get the decimal value out.

my library looks like

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));

For a simple solution you could do couple of tricks, 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 also comes with an endianness library: https://www.boost.org/doc/libs/1_74_0/libs/endian/doc/html/endian.html#buffers

You can use the built in types, like:

  • big_int32_t
  • little_int16_t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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