在编译时使用C ++ 11编程endianness [英] Finding endian-ness programatically at compile-time using C++11

查看:175
本文介绍了在编译时使用C ++ 11编程endianness的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这个主题中提到了许多问题,但是到目前为止找不到任何解决方案。这里提到了一个自然的解决方案:在编译时确定endianness

然而,上述相关问题在评论&同样的答案。

I have referred many questions in SO on this topic, but couldn't find any solution so far. One natural solution was mentioned here: Determining endianness at compile time.
However, the related problems mentioned in the comments & the same answer.

有了一些修改,我能够编译一个类似的解决方案与g ++& clang ++( -std = c ++ 11 )没有任何警告。

With some modifications, I am able to compile a similar solution with g++ & clang++ (-std=c++11) without any warning.

static_assert(sizeof(char) == 1, "sizeof(char) != 1");
union U1
{
  int i;
  char c[sizeof(int)];
};  
union U2
{ 
  char c[sizeof(int)];
  int i;
};  

constexpr U1 u1 = {1};
constexpr U2 u2 = {{1}};
constexpr bool IsLittleEndian ()
{ 
  return u1.i == u2.c[0];  // ignore different type comparison
}   

static_assert(IsLittleEndian(), "The machine is BIG endian");

演示

这可以被认为是确定性方法来决定字节序,还是错过类型冲突或其他东西?

Can this be considered a deterministic method to decide the endian-ness or does it miss type-punning or something else?

IsLittleEndian()与等同于
解决方案

c $ c> true ):

Your attempt is no different from this obviously non-working one (where IsLittleEndian() is identical to true):

constexpr char c[sizeof(int)] = {1};
constexpr int i = {1};
constexpr bool IsLittleEndian ()
{ 
  return i == c[0];  // ignore different type comparison
}   

static_assert(IsLittleEndian(), "The machine is BIG endian");



我相信C ++ 11不提供手段来编程性地确定目标平台的字节顺序在编译时。我的参数是,在运行时中执行该检查的唯一有效方法是使用 unsigned char检查 int 变量指针(因为其他类型的打孔方式不可避免地包含未定义的行为):

I believe that C++11 doesn't provide means to programatically determine the endianness of the target platform during compile time. My argument is that the only valid way to perform that check during runtime is to examine an int variable using an unsigned char pointer (since other ways of type punning inevitably contain undefined behavior):

const uint32_t i = 0xffff0000;

bool isLittleEndian() {
    return 0 == *reinterpret_cast<const unsigned char*>(&i);
}

C ++ 11不允许使此函数 constexpr ,因此无法在编译期间执行此检查。

C++11 doesn't allow to make this function constexpr, therefore this check cannot be performed during compile time.

这篇关于在编译时使用C ++ 11编程endianness的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆