Skip to content

Commit

Permalink
std::math::big: add bitwise not operator to the Int structure
Browse files Browse the repository at this point in the history
  • Loading branch information
mertcandav committed Mar 10, 2024
1 parent 3961790 commit 05a05d6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions std/math/big/int.jule
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,22 @@ impl Int {
ret self.cmp(y) == 0
}

// Bitwise not.
pub fn bit_not(self): Int {
let mut r = clone(self)
if r.neg {
sub_one(r.nat.bits)
r.nat.fit()
} else {
let carry = add_one(r.nat.bits)
if carry == 0b1 {
r.nat.bits = append(r.nat.bits, 0b1)
}
}
r.neg = !r.neg
ret r
}

// Reports whether number is odd.
pub fn odd(self): bool {
ret self.nat.odd()
Expand Down
18 changes: 18 additions & 0 deletions std/math/big/int_test.jule
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ static cases_int_mod = [
["1010", "+", "10000000000", "-", "1111110110", "-"],
]

static cases_int_bit_not: [][]i64 = [
[-20, 19],
[-90, 89],
[20, -21],
[90, -91],
]

fn test_common_int_op(mut &t: &T, op: str, &cases: [][]str) {
for _, c in cases {
let mut n1 = Int.from_bits(c[0], c[1] == "-") else {
Expand Down Expand Up @@ -130,6 +137,17 @@ fn test_int_mod(mut t: &T) {
test_common_int_op(t, "%", cases_int_mod)
}

#test
fn test_int_bit_not(mut t: &T) {
for _, c in cases_int_bit_not {
let i = Int.new(c[0])
let r = ^i
if (r.to_i64()!) != c[1] {
t.errorf("^{} != {}", c[0], c[1])
}
}
}

#test
fn test_int_lt(mut t: &T) {
t.assert(!Int.from_bits("1011010", false)!.lt(Int.from_bits("00001011010", false)!), "1) 1011010 < 00001011010")
Expand Down

0 comments on commit 05a05d6

Please sign in to comment.