位移位可移植性
Bit shift portability
本文关键字:可移植性 更新时间:2023-10-16
我的问题相当直接,此代码可移植?
#include <cstdint>
#ifndef ECS_INT
#define ECS_INT uint32_t
#endif
#ifndef ECS_MAX_NB_COMPONENTS
#define ECS_MAX_NB_COMPONENTS 255
#endif
static constexpr uint8_t FIND_MAX_NUMBER_OF_BITS(uint64_t base) {
//! Round to upper pow2
base--;
base |= base >> 1;
base |= base >> 2;
base |= base >> 4;
base |= base >> 8;
base |= base >> 16;
base |= base >> 32;
base++;
//! Check bits number
uint8_t counter = 0;
while (!(base & (1 << counter)))
++counter;
return counter;
}
static constexpr const ECS_INT INVALID_INDEX = ((ECS_INT) - 1);
static constexpr const uint8_t ECS_INT_MAX_BITS = FIND_MAX_NUMBER_OF_BITS(INVALID_INDEX) + 1;
static constexpr const uint8_t ECS_COMPONENT_MAX_BITS = FIND_MAX_NUMBER_OF_BITS(ECS_MAX_NB_COMPONENTS);
我不是对位的专家,但我认为该语言允许这是可移植的。也许我应该使用std::bitset
之类的东西?
-
1 << counter
应该是(uint64_t)1 << counter
,否则当counter
到达sizeof(int) * CHAR_BIT
时,它是未定义的行为(并且在少于一个小时时实现定义)。 - 即使修复了此操作,循环也将评估某些输入的
(uint64_t)1 << 64
,即未定义的行为,因此您需要添加预检查或循环条件以防止这种情况。
相关文章:
- C++Union/Struct位域的实现和可移植性
- 静态库可移植性
- C++:Unicode 字符串文字的可移植性
- 如何使Visual Studio 2017 C++项目在计算机之间更具可移植性
- 在为视频游戏实施基本的二进制序列化时,请担心可移植性
- 重写类以使其更通用,以实现可移植性
- Visual Studio 2015 <=> QtCreator 5 (c++) 代码可移植性
- 通过虚拟接口类导出C 类的可移植性
- 位移位可移植性
- 如何在Visual Studio中进行串行端口编程C++Windows和Linux之间的可移植性?
- 提高 Python 可移植性问题
- 库如何在不同的操作系统之间实现可移植性
- 使用C 11 /最近的G 版本(4.7 / 4.6)的可移植性
- 模板函数实例化的可移植性问题
- XCode、命名空间、C++和代码可移植性
- 嵌入式C++项目 - 需要支持智能指针.可能的可移植性问题
- 使用指针遍历数组的可移植性
- 头文件中内联自由函数的可移植性
- 文件IO中的可移植性问题
- 在不使用元素复制赋值运算符的情况下复制向量 - 可移植性