bigint: Add count_bits and more prep.

This commit is contained in:
Jeroen van Rijn
2021-08-11 20:59:50 +02:00
parent dfd5a993a2
commit 905d5459a9
4 changed files with 41 additions and 20 deletions
+23
View File
@@ -217,6 +217,29 @@ minus_one :: proc(a: ^Int, minimize := false) -> (err: Error) {
return .OK;
}
/*
Count bits in an `Int`.
*/
count_bits :: proc(a: ^Int) -> (count: int) {
assert_initialized(a);
/*
Fast path for zero.
*/
if is_zero(a) {
return 0;
}
/*
Get the number of DIGITs and use it.
*/
count = (a.used - 1) * _DIGIT_BITS;
/*
Take the last DIGIT and count the bits in it.
*/
clz := int(intrinsics.count_leading_zeros(a.digit[a.used - 1]));
count += (_DIGIT_TYPE_BITS - clz);
return;
}
/*
Internal helpers.
*/