fastest way to determine if a bit is set in a integer data type

后端 未结 3 1505
面向向阳花
面向向阳花 2020-12-10 22:49

I have a method that computes a hash value as per some specific algorithm.

uint8_t cal_hash(uint64_t _in_data) {
    uint8_t hash;
    // algorithm
    // bi         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 23:34

    Your first concern should be to have a correct and portable version. Compilers nowadays will then optimize such bit operations quite cleverly.

    You should always take care that the mask you are using corresponds to the data type that you are testing. Using an int or unsigned might not be enough since you are interested in the bits of a uint64_t and shifting for more than there are bits is undefined behavior.

    In your case you would probably use something like

    (UINT64_C(1) << (n))
    

    for the mask. If you want to do this in a more generic way you'd have to obtain a 1 of your base type by something like

    (1 ? 1U : (X))
    

    alltogether in a macro

    #define MASK(X, N) ((1 ? 1U : (X)) << (N))
    

    and then the test could look like

    #define BIT(X, N) !!((X) & MASK(X, N))
    

提交回复
热议问题