Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ auto type signed to/from unsigned conversion

Tags:

c++

c++11

c++14

I want to write a function that performs bit-wise operations on a parameter that is auto type.

  • The type passed in might be unsigned int or int type (with differing widths).
  • I only want to perform bit-wise operations on unsigned types.

I need an operator that returns the unsigned version of the original data type. In the function example below the "operator" unsigned_type would give me the data type that value has but insure it is unsigned.

  • int -> unsigned int
  • int16_t -> uint16_t
  • uint16_t -> uint16_t

Function example:

auto bit_shifting_and_mask(auto value) -> decltype(value)
{
    unsigned_type(value) unsigned_value = static_cast<unsigned_type(value)>(value);

    unsigned_value >>= 8u;       // Contrived bit manipulation
    unsigned_value &= 0xABCDu;   // here ...

    return static_cast<decltype(value)>(unsigned_value);
}

Is there some means to perform the operation unsigned_type against a data type obtained from decltype?

Thanks.

like image 426
natersoz Avatar asked Apr 12 '26 14:04

natersoz


1 Answers

C++11 has a std::make_unsigned utility in <type_traits>:

auto bit_shifting_and_mask(auto value) -> decltype(value)
{
    auto unsigned_value = static_cast<std::make_unsigned<decltype(value)>::type>(value);

    unsigned_value >>= 8u;       // Contrived bit manipulation
    unsigned_value &= 0xABCDu;   // here ...

    return static_cast<decltype(value)>(unsigned_value);
}

With C++14, you can simplify further by using std::make_unsigned_t instead of std::make_unsigned::type.

like image 158
Zrax Avatar answered Apr 15 '26 02:04

Zrax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!