Search code examples
c++boost-asioendianness

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

Solution

  • 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