[int.to_bytes(size, byteorder)](http://docs.micropython.org/en/latest/pyboard/library/builtins.html?highlight=to_bytes#int.to_bytes) requires one to know how many bytes - `size` - the output is but `int.bit_length()` is not implemented. ```Py >>> (1024).to_bytes(2, byteorder='big') b'\x04\x00' >>> (1024).to_bytes(10, byteorder='big') b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00' >>> (-1024).to_bytes(10, byteorder='big', signed=True) b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00' >>> x = 1000 >>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little') b'\xe8\x03' ```
Activity
dmazzella commentedon Aug 20, 2018
Attached a patch file that implement int.bit_length()
int_length.zip
adritium commentedon Aug 20, 2018
@dmazzella
If you went to the trouble to implement it, why not submit a pull-request?
C4 commentedon Mar 7, 2019
+1 for getting this added in.
Merge pull request micropython#4065 from weblate/weblate-circuitpytho…
rkagerer commentedon Feb 26, 2023
Has this still not been merged?
dpgeorge commentedon Feb 26, 2023
There is no pull request for this feature, so nothing to review and merge.
massimosala commentedon May 30, 2023
Hi Damiano
I request for bit_length on #11618 and I discover your work, thank to @dlech
It is the first time I see mpn/mpz, but reading its header it seems to me this optimization is possible:
How can we make this a PR ?
Hmh, if there's any doubts about its impact on flash space... what about an implementation that only works on CPU native integers?
I mean in your code taking away the mpn/mpz stuff, something like...
For cases (computing custom hashes, bit-banging, ...) where I see _ bit_length _ useful, you use at most 32 bit usigned int.
If it's not blasphemy to have a specialized version, I also ask for the implementation of bit_count
It is not present in Python, but here we are in Micropython and we work close to metal. Again for the same use cases mentioned above.
These specialized version (not mpn/mpz) of bit_length and bit_count will take a few bytes.
dmazzella commentedon May 31, 2023
Ciao Massimo,
I am attaching an updated version of the patch file to make
int.bit_lengthwork.this patch enable
MICROPY_INT_BIT_LENGTHinto the fileports/unix/variants/mpconfigvariant_common.hand unix port can be used for test.Try it and let me know if it works correctly.
this is a test for him, create the file
int_bit_length.pyinto the foldertests/basics/and paste:If everything works correctly I will proceed to create a PR for this
Greetings,
D.
int_bit_length.patch
massimosala commentedon May 31, 2023
Ciao Damiano
What about the possible optimization in the mpn/mpz code path?
For the testing: sorry, I just started developing on MP and I still haven't tried to install the toolchain and compile a firmware.
dmazzella commentedon Jun 1, 2023
For this we can wait tests/PR