◐ Shell
reader mode source ↗
From cppreference.com
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)    
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
 
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

See also

(C++29)
shifts to the right without the possibility of undefined behavior
(function template) [edit]
(C++20)
computes the result of bitwise left-rotation
(function template) [edit]
(C++20)
computes the result of bitwise right-rotation
(function template) [edit]