mirror of
https://github.com/pocketpy/pocketpy
synced 2025-10-20 03:20:18 +00:00
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:
parent
c77fef35a2
commit
8ca7e9f6cf
@ -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); });
|
||||
|
@ -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
|
||||
|
Loading…
x
Reference in New Issue
Block a user