-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add Int#bit_length #8924
Add Int#bit_length #8924
Conversation
Co-Authored-By: Vladislav Zarakovsky <vlad.zar@gmail.com>
spec/std/int_spec.cr
Outdated
it "#bit_length" do | ||
0.bit_length.should eq(0) | ||
(1..100).each do |i| | ||
i.bit_length.should eq(Math.log2(i).to_i + 1) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is testing that the result of bit_length
matches some mathematical formula. But it has about as much to do with the expected answers as the actual implementation of the method. Should you then have to write tests for this mathematical formula?
Tests shouldn't have logic, I'd suggest checking actual inputs.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Things like 0b1000
and 0b111.bit_length
might look nice
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good idea. Done!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice, thanks. But I think it still needs some checks specifically with "1+all-zeros" (like 0b1000
) and "all-ones" (0b111
) to catch off-by-one errors.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How about now?
* Add Int#bit_length * Update src/int.cr Co-Authored-By: Vladislav Zarakovsky <vlad.zar@gmail.com> * Simpler Int#bit_length specs * Spec for Int#bit_length negative values * Let Int#bit_length work for BigInt * More specs... * Be nice with Windows Co-authored-by: Vladislav Zarakovsky <vlad.zar@gmail.com>
Will be useful to implement https://forum.crystal-lang.org/t/integer-sqrt-in-stdlib . It's probably also a generally useful method. Also available in Ruby.