Skip to content

Commit

Permalink
Add bits package with add function
Browse files Browse the repository at this point in the history
  • Loading branch information
hextrust-0 committed May 9, 2024
1 parent ab9a4cd commit f0b3fea
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions pkg/bits/bits.mpcl
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// -*- go -*-

package bits

// Add returns the sum with carry of x, y and carry: sum = x + y + carry.
// The carry input must be 0 or 1; otherwise the behavior is undefined.
// The carryOut output is guaranteed to be 0 or 1.
//
// This function's execution time does not depend on the inputs.
func Add(x, y, carry uint) (sum, carryOut uint) {
sum = x + y + carry
// The sum will overflow if both top bits are set (x & y) or if one of them
// is (x | y), and a carry from the lower place happened. If such a carry
// happens, the top bit will be 1 + 0 + 1 = 0 (&^ sum).
carryOut = ((x & y) | ((x | y) &^ sum)) >> (size(carry)-1)
return
}

0 comments on commit f0b3fea

Please sign in to comment.