add bit_length method to int. (#233)

* add bit_length method to int.

* Update pocketpy.cpp

* Update 01_int.py

* Update 01_int.py

---------

Co-authored-by: BLUELOVETH <blueloveTH@foxmail.com>
This commit is contained in:
ykiko 2024-03-28 19:51:39 +08:00 committed by GitHub
parent c77fef35a2
commit 8ca7e9f6cf
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 1 deletions

View File

@ -444,6 +444,14 @@ void init_builtins(VM* _vm) {
return VAR(_CAST(i64, _0) % rhs);
});
_vm->bind_method<0>(VM::tp_int, "bit_length", [](VM* vm, ArgsView args) {
i64 x = _CAST(i64, args[0]);
if(x < 0) x = -x;
int bits = 0;
while(x){ x >>= 1; bits++; }
return VAR(bits);
});
_vm->bind__repr__(VM::tp_int, [](VM* vm, PyObject* obj) { return VAR(std::to_string(_CAST(i64, obj))); });
_vm->bind__neg__(VM::tp_int, [](VM* vm, PyObject* obj) { return VAR(-_CAST(i64, obj)); });
_vm->bind__hash__(VM::tp_int, [](VM* vm, PyObject* obj) { return _CAST(i64, obj); });

View File

@ -52,6 +52,18 @@ assert x == 3
assert str(1) == '1'
assert repr(1) == '1'
# test bit_length
assert (1).bit_length() == 1
assert (2).bit_length() == 2
assert (3).bit_length() == 2
assert (-1).bit_length() == 1
assert (-2).bit_length() == 2
assert (-3).bit_length() == 2
assert (123123123123123).bit_length() == 47
assert (-3123123123).bit_length() == 32
# test int()
assert int() == 0
assert int(True) == 1