Right shift positive `x` by positive `bits`, rounded half to even
| 397 | |
| 398 | // Right shift positive `x` by positive `bits`, rounded half to even |
| 399 | static Decimal128 RoundedRightShift(const Decimal128& x, int bits) { |
| 400 | if (bits == 0) { |
| 401 | return x; |
| 402 | } |
| 403 | int64_t result_hi = x.high_bits(); |
| 404 | uint64_t result_lo = x.low_bits(); |
| 405 | uint64_t shifted = 0; |
| 406 | while (bits >= 64) { |
| 407 | // Retain the information that set bits were shifted right. |
| 408 | // This is important to detect an exact half. |
| 409 | shifted = result_lo | (shifted > 0); |
| 410 | result_lo = result_hi; |
| 411 | result_hi >>= 63; // for sign |
| 412 | bits -= 64; |
| 413 | } |
| 414 | if (bits > 0) { |
| 415 | shifted = (result_lo << (64 - bits)) | (shifted > 0); |
| 416 | result_lo >>= bits; |
| 417 | result_lo |= static_cast<uint64_t>(result_hi) << (64 - bits); |
| 418 | result_hi >>= bits; |
| 419 | } |
| 420 | // We almost have our result, but now do the rounding. |
| 421 | constexpr uint64_t kHalf = 0x8000000000000000ULL; |
| 422 | if (shifted > kHalf) { |
| 423 | // Strictly more than half => round up |
| 424 | result_lo += 1; |
| 425 | result_hi += (result_lo == 0); |
| 426 | } else if (shifted == kHalf) { |
| 427 | // Exactly half => round to even |
| 428 | if ((result_lo & 1) != 0) { |
| 429 | result_lo += 1; |
| 430 | result_hi += (result_lo == 0); |
| 431 | } |
| 432 | } else { |
| 433 | // Strictly less than half => round down |
| 434 | } |
| 435 | return Decimal128{result_hi, result_lo}; |
| 436 | } |
| 437 | |
| 438 | template <typename Real> |
| 439 | static Result<Decimal128> FromPositiveRealApprox(Real real, int32_t precision, |
nothing calls this directly
no outgoing calls
no test coverage detected