BitConverter equivalent in C ++

0

I'm having a problem, in C# I did the following function, but when trying to pass the program to C++ with the IDE Qt5.7 I find the problem that BitConverter is reserved word of C#

short ConvertBytesToShort(byte msb, byte lsb){
if(BitConverter.IsLittleEndian)
   return BitConverter.ToInt16(new byte[2] {(byte)lsb , (byte)msb }, 0);
else
   return BitConverter.ToInt16(new byte[2] {(byte)msb , (byte)lsb }, 0);
}
    
asked by Aarón Gutiérrez 26.07.2017 в 22:09
source

1 answer

1

Presumably the C ++ 20 standard will incorporate in type_traits functionality to differentiate the architectures.

In that case your C ++ code might look something like this:

#include <type_traits>
#include <cstdint>

uint16_t ConvertBytesToShort(uint8_t msb, uint8_t lsb)
{
  if( std::endian::native == std::endian::big )
    return (static_cast<uint16_t>(lsb) << 8) + msb;
  else if( std::endian::native == std::endian::little )
     return (static_cast<uint16_t>(msb) << 8) + lsb;
  else
    // te faltaria tratar este caso
}

While we wait for the 3 years that remain until this standard sees the light you can use a solution such that:

C ++ 17

#include <cstdint>

constexpr bool is_big_endian()
{
  union
  {
    uint32_t intDummy;
    unsigned char c[4];
  } uTest = { 0x01020304 };

  return uTest.c[0] == 1; 
}

uint16_t ConvertBytesToShort(uint8_t msb, uint8_t lsb){
  if( is_big_endian() )
     return (static_cast<uint16_t>(lsb) << 8) + msb;
  else
     return (static_cast<uint16_t>(msb) << 8) + lsb;
}

C ++ 11 and earlier

#include <cstdint>

bool is_big_endian()
{
  union
  {
    uint32_t intDummy;
    unsigned char c[4];
  } uTest = { 0x01020304 };

  return uTest.c[0] == 1; 
}

uint16_t ConvertBytesToShort(uint8_t msb, uint8_t lsb){
  if( is_big_endian() )
     return (static_cast<uint16_t>(lsb) << 8) + msb;
  else
     return (static_cast<uint16_t>(msb) << 8) + lsb;
}
    
answered by 27.07.2017 / 00:34
source