From 8ca7e9f6cffd8da23f8d8ebe8113e8e5a3114123 Mon Sep 17 00:00:00 2001 From: ykiko Date: Thu, 28 Mar 2024 19:51:39 +0800 Subject: [PATCH] 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 --- src/pocketpy.cpp | 10 +++++++++- tests/01_int.py | 12 ++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/pocketpy.cpp b/src/pocketpy.cpp index 20addd09..37284b63 100644 --- a/src/pocketpy.cpp +++ b/src/pocketpy.cpp @@ -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); }); @@ -1625,4 +1633,4 @@ CodeObject_ VM::compile(std::string_view source, const Str& filename, CompileMod } } -} // namespace pkpy \ No newline at end of file +} // namespace pkpy diff --git a/tests/01_int.py b/tests/01_int.py index a1cb61a3..2c13964c 100644 --- a/tests/01_int.py +++ b/tests/01_int.py @@ -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