Gero
Gero

Reputation: 21

Getting the high part of signed integer multiplication in C++

How can I manually calculate the high part for a signed multiplication in C++? Like Getting the high part of 64 bit integer multiplication (unsigned only), but how do I calculate carry/borrow?

I do not mean that cast in a larger type (thats simple), but really manual calculation, so it works also with int128_t. My goal is to write a template function that always returns the correct high-part for signed and unsigned arguments (u/int8..128_t):

template <typename Type>
constexpr Type mulh(const Type& op1, const Type& op2) noexcept
{
    if constexpr (std::is_signed_v<Type>)   return ???;
    else                                    return see link;
}

Upvotes: 1

Views: 322

Answers (2)

&#214;&#246; Tiib
&#214;&#246; Tiib

Reputation: 10979

It seems that you are implementing things that are usually available as compiler builtin functions.

Implementing those in standard C++ results with less efficient code. That can be still fun as mental exercise but then why you ask us to spoil it as whole?

Upvotes: 1

Rob Lambden
Rob Lambden

Reputation: 2293

If you can do signed, then you could convert unsigned to signed x=(x<0)?x*-1:x get the result and then calculate the sign afterwards z=((x<0)!=(y<0))?z*-1:z

This works becuase the magnitude of a signed integer of arbitraty length is always going to fit into an unsigned integer of the same length, and you know that if both numbers are negative or positive the answer will be positive, if only one of them is negative it will be negative.

Upvotes: 0

Related Questions