Sfoglia il codice sorgente

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>
ykiko 1 anno fa
parent
commit
8ca7e9f6cf
2 ha cambiato i file con 21 aggiunte e 1 eliminazioni
  1. 9 1
      src/pocketpy.cpp
  2. 12 0
      tests/01_int.py

+ 9 - 1
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
+}   // namespace pkpy

+ 12 - 0
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