【问题标题】:How to determine endianness at compile-time?如何在编译时确定字节顺序?
【发布时间】:2023-03-25 03:09:01
【问题描述】:

如何在编译时确定我的平台是小端还是大端?我已经看到了许多在运行时使用强制转换来确定的方法,以及一些依赖于平台的选项。是否有可移植或标准的方法来执行此操作?

constexpr bool is_little_endian = ?;

【问题讨论】:

标签: c++


【解决方案1】:

C++20 将std::endian 添加到<type_traits>,可以在 constexpr 上下文中使用。

Live example of below code:

if constexpr (std::endian::native == std::endian::little) {
    std::cout << "litle endian\n";
} else if constexpr(std::endian::native == std::endian::big) {
    std::cout << "big endian\n";
} else {
    std::cout << "something silly\n";
}

【讨论】:

  • != little 并不严格暗示大端。有一些不太常见的奇怪字节顺序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-15
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2010-11-16
相关资源
最近更新 更多