From cppreference.com
| Defined in header <bit>
|
||
template< class T, class S >
constexpr T shl( T x, S s ) noexcept;
|
(since C++29) | |
Returns \( \lfloor x \times 2^{s} \rfloor \)⌊x · 2s
⌋ rounded towards negative infinity, and truncated to fit into T.
Parameters
| x | - | value of unsigned integer type |
| s | - | number of positions to shift |
Return value
\( \lfloor x \times 2^{s} \rfloor \)⌊x · 2s
⌋ truncated to the result type.
Notes
Unlike the << operator, std::shl never has undefined behavior.
Shifting takes place as if by shifting to the left by a single bit s times, or shifting to the right by a single bit -s times if s is negative, except that -s cannot overflow.
| Feature-test macro | Value | Std | Feature |
|---|---|---|---|
__cpp_lib_bitops |
202606L |
(C++20) | Better shifting |
Possible implementation
template<class T, class S> // TODO: constraints
constexpr T shl(T x, S s) noexcept
{
constexpr auto width = S(std::numeric_limits<std::make_unsigned_t<T>>::digits);
if constexpr (std::is_signed_v<S>)
{
if (s < 0)
return s <= -width ? T(x < 0 ? -1 : 0) : x >> -s;
}
return s >= width ? T(0) : x << s;
}
|
Example
| This section is incomplete Reason: no example |
See also
(C++29) |
shifts to the right without the possibility of undefined behavior (function template) |
(C++20) |
computes the result of bitwise left-rotation (function template) |
(C++20) |
computes the result of bitwise right-rotation (function template) |