Is static_cast(-1) the right way to generate all-one-bits data without numeric_limits?

后端 未结 5 1745
温柔的废话
温柔的废话 2021-02-05 03:28

I\'m writing C++ code in an environment in which I don\'t have access to the C++ standard library, specifically not to std::numeric_limits. Suppose I want to implem

5条回答
  •  甜味超标
    2021-02-05 04:08

    Use the bitwise NOT operator ~ on 0.

    T allOnes = ~(T)0;
    

    A static_cast(-1) assumes two's complement, which is not portable. If you are only concerned about unsigned types, hvd's answer is the way to go.

    Working example: https://ideone.com/iV28u0

提交回复
热议问题