2016-12-04 75 views
0

我的問題相當直接,這段代碼是否便攜?移位便攜

#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

回答

3
  • 1 << counter(uint64_t)1 << counter否則它是未定義的行爲時counter達到sizeof(int) * CHAR_BIT(和實現定義的比一個更小時)。
  • 即使修復後,循環將評估(uint64_t)1 << 64的一些輸入,這是未定義的行爲,所以你需要添加預檢或循環條件,以防止這種情況。
+0

(uint64_t)1 << 64是否爲最大值爲no的情況?所以我不知道我是否需要64位的這種情況?最大63位呢?你知道更好的方法來檢查嗎? –

+0

如果'counter == 64',或者其他東西 –

+0

你可以打破循環哦,你是對的,這只是一個算法錯誤。我很害怕沒有抱歉。不管怎樣,謝謝:) –