2's complement subtraction in swift

In Swift, we can perform 2's complement subtraction using the bit-wise NOT operator (~) and the bit-wise AND operator (&).

Here's an example of how to subtract 6 from 10 using 2's complement:

main.swift
let a = 0b1010 // 10 in binary
let b = 0b0110 // 6 in binary

let diff = a + (~b + 1)

print(diff) // Outputs -4, which is the 2's complement (-0b100) representation of the difference between 10 and 6
201 chars
7 lines

In this example, we first convert the numbers 10 and 6 to binary using the 0b prefix. We then calculate the 2's complement by taking the bit-wise NOT of b and adding 1. Finally, we add this 2's complement representation of b to a. The result is the 2's complement representation of the difference between 10 and 6, which is -4 in this case.

gistlibby LogSnag