Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 implement

template <typename T> constexpr T all_ones( /* ... */ ) 

Focusing on unsigned integral types, what do I put there? Specifically, is static_cast<T>(-1) good enough? (Other types I could treat as an array of unsigned chars based on their size I guess.)

like image 248
einpoklum Avatar asked Apr 17 '16 11:04

einpoklum


1 Answers

Use the bitwise NOT operator ~ on 0.

T allOnes = ~(T)0; 

A static_cast<T>(-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

like image 96
Leandros Avatar answered Sep 18 '22 18:09

Leandros