diff options
author | Damien George <damien.p.george@gmail.com> | 2015-04-25 23:16:39 +0100 |
---|---|---|
committer | Damien George <damien.p.george@gmail.com> | 2015-04-25 23:16:39 +0100 |
commit | 271d18eb08ec488ee45f8e6cd852e8236074f082 (patch) | |
tree | f5ba5d1b28cb48e72334fb079a5d6ef148083970 /py/objint.c | |
parent | 7c8b4c1a8b8278d864649c127857e34a6bd29504 (diff) | |
download | micropython-271d18eb08ec488ee45f8e6cd852e8236074f082.tar.gz micropython-271d18eb08ec488ee45f8e6cd852e8236074f082.zip |
py: Support conversion of bignum to bytes.
This gets int.to_bytes working for bignum, and also struct.pack with 'q'
and 'Q' args on 32-bit machines.
Addresses issue #1155.
Diffstat (limited to 'py/objint.c')
-rw-r--r-- | py/objint.c | 18 |
1 files changed, 9 insertions, 9 deletions
diff --git a/py/objint.c b/py/objint.c index 64faed636f..7c527d4ae7 100644 --- a/py/objint.c +++ b/py/objint.c @@ -35,6 +35,7 @@ #include "py/objstr.h" #include "py/runtime0.h" #include "py/runtime.h" +#include "py/binary.h" #if MICROPY_PY_BUILTINS_FLOAT #include <math.h> @@ -398,12 +399,10 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_fun_obj, 2, 3, int_fro STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(int_from_bytes_obj, (const mp_obj_t)&int_from_bytes_fun_obj); STATIC mp_obj_t int_to_bytes(mp_uint_t n_args, const mp_obj_t *args) { - // TODO: Support long ints // TODO: Support byteorder param (assumes 'little') // TODO: Support signed param (assumes signed=False) (void)n_args; - mp_int_t val = mp_obj_int_get_checked(args[0]); mp_uint_t len = MP_OBJ_SMALL_INT_VALUE(args[1]); vstr_t vstr; @@ -411,13 +410,14 @@ STATIC mp_obj_t int_to_bytes(mp_uint_t n_args, const mp_obj_t *args) { byte *data = (byte*)vstr.buf; memset(data, 0, len); - if (MP_ENDIANNESS_LITTLE) { - memcpy(data, &val, len < sizeof(mp_int_t) ? len : sizeof(mp_int_t)); - } else { - while (len--) { - *data++ = val; - val >>= 8; - } + #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE + if (!MP_OBJ_IS_SMALL_INT(args[0])) { + mp_obj_int_to_bytes_impl(args[0], false, len, data); + } else + #endif + { + mp_int_t val = MP_OBJ_SMALL_INT_VALUE(args[0]); + mp_binary_set_int(MIN((size_t)len, sizeof(val)), false, data, val); } return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); |