multipliedFullWidth(by:)
Returns a tuple containing the high and low parts of the result of multiplying this value by the given value.
func multipliedFullWidth(by other: Int) -> (high: Int, low: Int.Magnitude)
Parameters
- other
The value to multiply this value by.
Returns
A tuple containing the high and low parts of the result of multiplying this value and other
.
Overview
Use this method to calculate the full result of a product that would otherwise overflow. Unlike traditional truncating multiplication, the multipliedFullWidth(by:)
method returns a tuple containing both the high
and low
parts of the product of this value and other
. The following example uses this method to multiply two UInt8
values that normally overflow when multiplied:
let x: UInt8 = 100
let y: UInt8 = 20
let result = x.multipliedFullWidth(by: y)
// result.high == 0b00000111
// result.low == 0b11010000
The product of x
and y
is 2000, which is too large to represent in a UInt8
instance. The high
and low
properties of the result
value represent 2000 when concatenated to form a double-width integer; that is, using result.high
as the high byte and result.low
as the low byte of a UInt16
instance.
let z = UInt16(result.high) << 8 | UInt16(result.low)
// z == 2000