## BinaryInteger

protocol BinaryInteger

An integer type with a binary representation.

Inheritance CustomStringConvertible, Hashable, Numeric, Strideable FixedWidthInteger, SignedInteger, UnsignedInteger associatedtype Words The Words type must conform to the RandomAccessCollection protocol with an Element type of UInt and Index type of `Int.

The BinaryInteger protocol is the basis for all the integer types provided by the standard library. All of the standard library's integer types, such as Int and UInt32, conform to BinaryInteger.

### Converting Between Numeric Types

You can create new instances of a type that conforms to the BinaryInteger protocol from a floating-point number or another binary integer of any type. The BinaryInteger protocol provides initializers for four different kinds of conversion.

#### Range-Checked Conversion

You use the default init(_:) initializer to create a new instance when you're sure that the value passed is representable in the new type. For example, an instance of Int16 can represent the value 500, so the first conversion in the code sample below succeeds. That same value is too large to represent as an Int8 instance, so the second conversion fails, triggering a runtime error.

let x: Int = 500
let y = Int16(x)
// y == 500

let z = Int8(x)
// Error: Not enough bits to represent...

When you create a binary integer from a floating-point value using the default initializer, the value is rounded toward zero before the range is checked. In the following example, the value 127.75 is rounded to 127, which is representable by the Int8 type. 128.25 is rounded to 128, which is not representable as an Int8 instance, triggering a runtime error.

let e = Int8(127.75)
// e == 127

let f = Int8(128.25)
// Error: Double value cannot be converted...

#### Exact Conversion

Use the init?(exactly:) initializer to create a new instance after checking whether the passed value is representable. Instead of trapping on out-of-range values, using the failable init?(exactly:) initializer results in nil.

let x = Int16(exactly: 500)
// x == Optional(500)

let y = Int8(exactly: 500)
// y == nil

When converting floating-point values, the init?(exactly:) initializer checks both that the passed value has no fractional part and that the value is representable in the resulting type.

let e = Int8(exactly: 23.0)       // integral value, representable
// e == Optional(23)

let f = Int8(exactly: 23.75)      // fractional value, representable
// f == nil

let g = Int8(exactly: 500.0)      // integral value, nonrepresentable
// g == nil

#### Clamping Conversion

Use the init(clamping:) initializer to create a new instance of a binary integer type where out-of-range values are clamped to the representable range of the type. For a type T, the resulting value is in the range T.min...T.max.

let x = Int16(clamping: 500)
// x == 500

let y = Int8(clamping: 500)
// y == 127

let z = UInt8(clamping: -500)
// z == 0

#### Bit Pattern Conversion

Use the init(truncatingIfNeeded:) initializer to create a new instance with the same bit pattern as the passed value, extending or truncating the value's representation as necessary. Note that the value may not be preserved, particularly when converting between signed to unsigned integer types or when the destination type has a smaller bit width than the source type. The following example shows how extending and truncating work for nonnegative integers:

let q: Int16 = 850
// q == 0b00000011_01010010

let r = Int8(truncatingIfNeeded: q)      // truncate 'q' to fit in 8 bits
// r == 82
//   == 0b01010010

let s = Int16(truncatingIfNeeded: r)     // extend 'r' to fill 16 bits
// s == 82
//   == 0b00000000_01010010

Any padding is performed by sign-extending the passed value. When nonnegative integers are extended, the result is padded with zeroes. When negative integers are extended, the result is padded with ones. This example shows several extending conversions of a negative value---note that negative values are sign-extended even when converting to an unsigned type.

let t: Int8 = -100
// t == -100
// t's binary representation == 0b10011100

let u = UInt8(truncatingIfNeeded: t)
// u == 156
// u's binary representation == 0b10011100

let v = Int16(truncatingIfNeeded: t)
// v == -100
// v's binary representation == 0b11111111_10011100

let w = UInt16(truncatingIfNeeded: t)
// w == 65436
// w's binary representation == 0b11111111_10011100

### Comparing Across Integer Types

You can use relational operators, such as the less-than and equal-to operators (< and ==), to compare instances of different binary integer types. The following example compares instances of the Int, UInt, and UInt8 types:

let x: Int = -23
let y: UInt = 1_000
let z: UInt8 = 23

if x < y {
print("\(x) is less than \(y).")
}
// Prints "-23 is less than 1000."

if z > x {
print("\(z) is greater than \(x).")
}
// Prints "23 is greater than -23."

### Initializers

init init(_:) Required

Creates an integer from the given floating-point value, rounding toward zero.

Any fractional part of the value passed as source is removed, rounding the value toward zero.

let x = Int(21.5)
// x == 21
let y = Int(-21.5)
// y == -21

If source is outside the bounds of this type after rounding toward zero, a runtime error may occur.

let z = UInt(-21.5)
// Error: ...the result would be less than UInt.min
• Parameter source: A floating-point value to convert to an integer. source must be representable in this type after rounding toward zero.

#### Declaration

init<T>(_ source: T) where T: BinaryFloatingPoint
init init(_:) Required

Creates a new instance from the given integer.

If the value passed as source is not representable in this type, a runtime error may occur.

let x = -500 as Int
let y = Int32(x)
// y == -500

// -500 is not representable as a 'UInt32' instance
let z = UInt32(x)
// Error
• Parameter source: An integer to convert. source must be representable in this type.

#### Declaration

init<T>(_ source: T) where T: BinaryInteger
init init(clamping:) Required

Creates a new instance with the representable value that's closest to the given integer.

If the value passed as source is greater than the maximum representable value in this type, the result is the type's max value. If source is less than the smallest representable value in this type, the result is the type's min value.

In this example, x is initialized as an Int8 instance by clamping 500 to the range -128...127, and y is initialized as a UInt instance by clamping -500 to the range 0...UInt.max.

let x = Int8(clamping: 500)
// x == 127
// x == Int8.max

let y = UInt(clamping: -500)
// y == 0
• Parameter source: An integer to convert to this type.

#### Declaration

init<T>(clamping source: T) where T: BinaryInteger
init init(truncatingIfNeeded:) Required

Creates a new instance from the bit pattern of the given instance by sign-extending or truncating to fit this type.

When the bit width of T (the type of source) is equal to or greater than this type's bit width, the result is the truncated least-significant bits of source. For example, when converting a 16-bit value to an 8-bit type, only the lower 8 bits of source are used.

let p: Int16 = -500
// 'p' has a binary representation of 11111110_00001100
let q = Int8(truncatingIfNeeded: p)
// q == 12
// 'q' has a binary representation of 00001100

When the bit width of T is less than this type's bit width, the result is sign-extended to fill the remaining bits. That is, if source is negative, the result is padded with ones; otherwise, the result is padded with zeros.

let u: Int8 = 21
// 'u' has a binary representation of 00010101
let v = Int16(truncatingIfNeeded: u)
// v == 21
// 'v' has a binary representation of 00000000_00010101

let w: Int8 = -21
// 'w' has a binary representation of 11101011
let x = Int16(truncatingIfNeeded: w)
// x == -21
// 'x' has a binary representation of 11111111_11101011
let y = UInt16(truncatingIfNeeded: w)
// y == 65515
// 'y' has a binary representation of 11111111_11101011
• Parameter source: An integer to convert to this type.

#### Declaration

init<T>(truncatingIfNeeded source: T) where T: BinaryInteger
init init?(exactly:) Required

Creates an integer from the given floating-point value, if it can be represented exactly.

If the value passed as source is not representable exactly, the result is nil. In the following example, the constant x is successfully created from a value of 21.0, while the attempt to initialize the constant y from 21.5 fails:

let x = Int(exactly: 21.0)
// x == Optional(21)
let y = Int(exactly: 21.5)
// y == nil
• Parameter source: A floating-point value to convert to an integer.

#### Declaration

init?<T>(exactly source: T) where T: BinaryFloatingPoint

### Instance Variables

var bitWidth Required

The number of bits in the current binary representation of this value.

This property is a constant for instances of fixed-width integer types.

#### Declaration

var bitWidth: Int
var trailingZeroBitCount Required

The number of trailing zeros in this value's binary representation.

For example, in a fixed-width integer type with a bitWidth value of 8, the number -8 has three trailing zeros.

let x = Int8(bitPattern: 0b1111_1000)
// x == -8
// x.trailingZeroBitCount == 3

If the value is zero, then trailingZeroBitCount is equal to bitWidth.

#### Declaration

var trailingZeroBitCount: Int
var words Required

A collection containing the words of this value's binary representation, in order from the least significant to most significant.

Negative values are returned in two's complement representation, regardless of the type's underlying implementation.

#### Declaration

var words: Self.Words

### Instance Methods

func isMultiple(of other: Self) -> Bool Required

Returns true if this value is a multiple of the given value, and false otherwise.

For two integers a and b, a is a multiple of b if there exists a third integer q such that a = q*b. For example, 6 is a multiple of 3 because 6 = 2*3. Zero is a multiple of everything because 0 = 0*x for any integer x.

Two edge cases are worth particular attention:

• Parameter other: The value to test.

#### Declaration

func isMultiple(of other: Self) -> Bool
func quotientAndRemainder(dividingBy rhs: Self) -> (quotient: Self, remainder: Self) Required

Returns the quotient and remainder of this value divided by the given value.

Use this method to calculate the quotient and remainder of a division at the same time.

let x = 1_000_000
let (q, r) = x.quotientAndRemainder(dividingBy: 933)
// q == 1071
// r == 757
• Parameter rhs: The value to divide this value by.

#### Declaration

func quotientAndRemainder(dividingBy rhs: Self) -> (quotient: Self, remainder: Self)
func signum() -> Self Required

Returns -1 if this value is negative and 1 if it's positive; otherwise, 0.

#### Declaration

func signum() -> Self

### Type Variables

var isSigned Required

A Boolean value indicating whether this type is a signed integer type.

Signed integer types can represent both positive and negative values. Unsigned integer types can represent only nonnegative values.

#### Declaration

var isSigned: Bool

### Type Methods

func %(lhs: Self, rhs: Self) -> Self Required

Returns the remainder of dividing the first value by the second.

The result of the remainder operator (%) has the same sign as lhs and has a magnitude less than rhs.magnitude.

let x = 22 % 5
// x == 2
let y = 22 % -5
// y == 2
let z = -22 % -5
// z == -2

For any two integers a and b, their quotient q, and their remainder r, a == b * q + r.

#### Declaration

static func %(lhs: Self, rhs: Self) -> Self
func %=(lhs: inout Self, rhs: Self) Required

Divides the first value by the second and stores the remainder in the left-hand-side variable.

The result has the same sign as lhs and has a magnitude less than rhs.magnitude.

var x = 22
x %= 5
// x == 2

var y = 22
y %= -5
// y == 2

var z = -22
z %= -5
// z == -2

#### Declaration

static func %=(lhs: inout Self, rhs: Self)
func &(lhs: Self, rhs: Self) -> Self Required

Returns the result of performing a bitwise AND operation on the two given values.

A bitwise AND operation results in a value that has each bit set to 1 where both of its arguments have that bit set to 1. For example:

let x: UInt8 = 5          // 0b00000101
let y: UInt8 = 14         // 0b00001110
let z = x & y             // 0b00000100
// z == 4

#### Declaration

static func &(lhs: Self, rhs: Self) -> Self
func &=(lhs: inout Self, rhs: Self) Required

Stores the result of performing a bitwise AND operation on the two given values in the left-hand-side variable.

A bitwise AND operation results in a value that has each bit set to 1 where both of its arguments have that bit set to 1. For example:

var x: UInt8 = 5          // 0b00000101
let y: UInt8 = 14         // 0b00001110
x &= y                    // 0b00000100

#### Declaration

static func &=(lhs: inout Self, rhs: Self)
func *(lhs: Self, rhs: Self) -> Self Required

Multiplies two values and produces their product.

The multiplication operator (*) calculates the product of its two arguments. For example:

2 * 3                   // 6
100 * 21                // 2100
-10 * 15                // -150
3.5 * 2.25              // 7.875

You cannot use * with arguments of different types. To multiply values of different types, convert one of the values to the other value's type.

let x: Int8 = 21
let y: Int = 1000000
Int(x) * y              // 21000000

#### Declaration

override static func *(lhs: Self, rhs: Self) -> Self
func *=(lhs: inout Self, rhs: Self) Required

Multiplies two values and stores the result in the left-hand-side variable.

#### Declaration

override static func *=(lhs: inout Self, rhs: Self)
func +(lhs: Self, rhs: Self) -> Self Required

Adds two values and produces their sum.

The addition operator (+) calculates the sum of its two arguments. For example:

1 + 2                   // 3
-10 + 15                // 5
-15 + -5                // -20
21.5 + 3.25             // 24.75

You cannot use + with arguments of different types. To add values of different types, convert one of the values to the other value's type.

let x: Int8 = 21
let y: Int = 1000000
Int(x) + y              // 1000021

#### Declaration

override static func +(lhs: Self, rhs: Self) -> Self
func +=(lhs: inout Self, rhs: Self) Required

Adds two values and stores the result in the left-hand-side variable.

#### Declaration

override static func +=(lhs: inout Self, rhs: Self)
func -(lhs: Self, rhs: Self) -> Self Required

Subtracts one value from another and produces their difference.

The subtraction operator (-) calculates the difference of its two arguments. For example:

8 - 3                   // 5
-10 - 5                 // -15
100 - -5                // 105
10.5 - 100.0            // -89.5

You cannot use - with arguments of different types. To subtract values of different types, convert one of the values to the other value's type.

let x: UInt8 = 21
let y: UInt = 1000000
y - UInt(x)             // 999979

#### Declaration

override static func -(lhs: Self, rhs: Self) -> Self
func -=(lhs: inout Self, rhs: Self) Required

Subtracts the second value from the first and stores the difference in the left-hand-side variable.

#### Declaration

override static func -=(lhs: inout Self, rhs: Self)
func /(lhs: Self, rhs: Self) -> Self Required

Returns the quotient of dividing the first value by the second.

For integer types, any remainder of the division is discarded.

let x = 21 / 5
// x == 4

#### Declaration

static func /(lhs: Self, rhs: Self) -> Self
func /=(lhs: inout Self, rhs: Self) Required

Divides the first value by the second and stores the quotient in the left-hand-side variable.

For integer types, any remainder of the division is discarded.

var x = 21
x /= 5
// x == 4

#### Declaration

static func /=(lhs: inout Self, rhs: Self)
func <<(lhs: Self, rhs: RHS) -> Self Required

Returns the result of shifting a value's binary representation the specified number of digits to the left.

The << operator performs a smart shift, which defines a result for a shift of any value.

The following example defines x as an instance of UInt8, an 8-bit, unsigned integer type. If you use 2 as the right-hand-side value in an operation on x, the value is shifted left by two bits.

let x: UInt8 = 30                 // 0b00011110
let y = x << 2
// y == 120                       // 0b01111000

If you use 11 as rhs, x is overshifted such that all of its bits are set to zero.

let z = x << 11
// z == 0                         // 0b00000000

Using a negative value as rhs is the same as performing a right shift with abs(rhs).

let a = x << -3
// a == 3                         // 0b00000011
let b = x >> 3
// b == 3                         // 0b00000011

#### Declaration

static func <<<RHS>(lhs: Self, rhs: RHS) -> Self where RHS: BinaryInteger
func <<=(lhs: inout Self, rhs: RHS) Required

Stores the result of shifting a value's binary representation the specified number of digits to the left in the left-hand-side variable.

The << operator performs a smart shift, which defines a result for a shift of any value.

The following example defines x as an instance of UInt8, an 8-bit, unsigned integer type. If you use 2 as the right-hand-side value in an operation on x, the value is shifted left by two bits.

var x: UInt8 = 30                 // 0b00011110
x <<= 2
// x == 120                       // 0b01111000

If you use 11 as rhs, x is overshifted such that all of its bits are set to zero.

var y: UInt8 = 30                 // 0b00011110
y <<= 11
// y == 0                         // 0b00000000

Using a negative value as rhs is the same as performing a right shift with abs(rhs).

var a: UInt8 = 30                 // 0b00011110
a <<= -3
// a == 3                         // 0b00000011

var b: UInt8 = 30                 // 0b00011110
b >>= 3
// b == 3                         // 0b00000011

#### Declaration

static func <<=<RHS>(lhs: inout Self, rhs: RHS) where RHS: BinaryInteger
func >>(lhs: Self, rhs: RHS) -> Self Required

Returns the result of shifting a value's binary representation the specified number of digits to the right.

The >> operator performs a smart shift, which defines a result for a shift of any value.

The following example defines x as an instance of UInt8, an 8-bit, unsigned integer type. If you use 2 as the right-hand-side value in an operation on x, the value is shifted right by two bits.

let x: UInt8 = 30                 // 0b00011110
let y = x >> 2
// y == 7                         // 0b00000111

If you use 11 as rhs, x is overshifted such that all of its bits are set to zero.

let z = x >> 11
// z == 0                         // 0b00000000

Using a negative value as rhs is the same as performing a left shift using abs(rhs).

let a = x >> -3
// a == 240                       // 0b11110000
let b = x << 3
// b == 240                       // 0b11110000

Right shift operations on negative values "fill in" the high bits with ones instead of zeros.

let q: Int8 = -30                 // 0b11100010
let r = q >> 2
// r == -8                        // 0b11111000

let s = q >> 11
// s == -1                        // 0b11111111

#### Declaration

static func >><RHS>(lhs: Self, rhs: RHS) -> Self where RHS: BinaryInteger
func >>=(lhs: inout Self, rhs: RHS) Required

Stores the result of shifting a value's binary representation the specified number of digits to the right in the left-hand-side variable.

The >>= operator performs a smart shift, which defines a result for a shift of any value.

The following example defines x as an instance of UInt8, an 8-bit, unsigned integer type. If you use 2 as the right-hand-side value in an operation on x, the value is shifted right by two bits.

var x: UInt8 = 30                 // 0b00011110
x >>= 2
// x == 7                         // 0b00000111

If you use 11 as rhs, x is overshifted such that all of its bits are set to zero.

var y: UInt8 = 30                 // 0b00011110
y >>= 11
// y == 0                         // 0b00000000

Using a negative value as rhs is the same as performing a left shift using abs(rhs).

var a: UInt8 = 30                 // 0b00011110
a >>= -3
// a == 240                       // 0b11110000

var b: UInt8 = 30                 // 0b00011110
b <<= 3
// b == 240                       // 0b11110000

Right shift operations on negative values "fill in" the high bits with ones instead of zeros.

var q: Int8 = -30                 // 0b11100010
q >>= 2
// q == -8                        // 0b11111000

var r: Int8 = -30                 // 0b11100010
r >>= 11
// r == -1                        // 0b11111111

#### Declaration

static func >>=<RHS>(lhs: inout Self, rhs: RHS) where RHS: BinaryInteger
func ^(lhs: Self, rhs: Self) -> Self Required

Returns the result of performing a bitwise XOR operation on the two given values.

A bitwise XOR operation, also known as an exclusive OR operation, results in a value that has each bit set to 1 where one or the other but not both of its arguments had that bit set to 1. For example:

let x: UInt8 = 5          // 0b00000101
let y: UInt8 = 14         // 0b00001110
let z = x ^ y             // 0b00001011
// z == 11

#### Declaration

static func ^(lhs: Self, rhs: Self) -> Self
func ^=(lhs: inout Self, rhs: Self) Required

Stores the result of performing a bitwise XOR operation on the two given values in the left-hand-side variable.

A bitwise XOR operation, also known as an exclusive OR operation, results in a value that has each bit set to 1 where one or the other but not both of its arguments had that bit set to 1. For example:

var x: UInt8 = 5          // 0b00000101
let y: UInt8 = 14         // 0b00001110
x ^= y                    // 0b00001011

#### Declaration

static func ^=(lhs: inout Self, rhs: Self)
func |(lhs: Self, rhs: Self) -> Self Required

Returns the result of performing a bitwise OR operation on the two given values.

A bitwise OR operation results in a value that has each bit set to 1 where one or both of its arguments have that bit set to 1. For example:

let x: UInt8 = 5          // 0b00000101
let y: UInt8 = 14         // 0b00001110
let z = x | y             // 0b00001111
// z == 15

#### Declaration

static func |(lhs: Self, rhs: Self) -> Self
func |=(lhs: inout Self, rhs: Self) Required

Stores the result of performing a bitwise OR operation on the two given values in the left-hand-side variable.

A bitwise OR operation results in a value that has each bit set to 1 where one or both of its arguments have that bit set to 1. For example:

var x: UInt8 = 5          // 0b00000101
let y: UInt8 = 14         // 0b00001110
x |= y                    // 0b00001111

#### Declaration

static func |=(lhs: inout Self, rhs: Self)
func ~(x: Self) -> Self Required

Returns the inverse of the bits set in the argument.

The bitwise NOT operator (~) is a prefix operator that returns a value in which all the bits of its argument are flipped: Bits that are 1 in the argument are 0 in the result, and bits that are 0 in the argument are 1 in the result. This is equivalent to the inverse of a set. For example:

let x: UInt8 = 5        // 0b00000101
let notX = ~x           // 0b11111010

Performing a bitwise NOT operation on 0 returns a value with every bit set to 1.

let allOnes = ~UInt8.min   // 0b11111111

Complexity: O(1).

#### Declaration

prefix static func ~(x: Self) -> Self

### Default Implementations

func <(x: Self, y: Self) -> Bool

Returns a Boolean value indicating whether the value of the first argument is less than that of the second argument.

This function is the only requirement of the Comparable protocol. The remainder of the relational operator functions are implemented by the standard library for any type that conforms to Comparable.

#### Declaration

@inlinable public static func <(x: Self, y: Self) -> Bool
func ==(x: Self, y: Self) -> Bool

Returns a Boolean value indicating whether two values are equal.

Equality is the inverse of inequality. For any values a and b, a == b implies that a != b is false.

#### Declaration

@inlinable public static func ==(x: Self, y: Self) -> Bool