py: Make int.to_bytes work on big endian machine.
Partly addresses issue #856.
This commit is contained in:
parent
a9bcd51dc7
commit
fcdb239815
26
py/objint.c
26
py/objint.c
|
@ -327,20 +327,28 @@ 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_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) {
|
STATIC mp_obj_t int_to_bytes(mp_uint_t n_args, const mp_obj_t *args) {
|
||||||
mp_int_t val = mp_obj_int_get_checked(args[0]);
|
|
||||||
|
|
||||||
uint len = MP_OBJ_SMALL_INT_VALUE(args[1]);
|
|
||||||
byte *data;
|
|
||||||
|
|
||||||
// TODO: Support long ints
|
// TODO: Support long ints
|
||||||
// TODO: Support byteorder param
|
// TODO: Support byteorder param (assumes 'little')
|
||||||
// TODO: Support signed param
|
// TODO: Support signed param (assumes signed=False)
|
||||||
|
|
||||||
|
mp_int_t val = mp_obj_int_get_checked(args[0]);
|
||||||
|
mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[1]);
|
||||||
|
|
||||||
|
byte *data;
|
||||||
mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
|
mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
|
||||||
memset(data, 0, len);
|
memset(data, 0, len);
|
||||||
memcpy(data, &val, len < sizeof(mp_int_t) ? len : sizeof(mp_int_t));
|
|
||||||
|
if (MP_ENDIANNESS_LITTLE) {
|
||||||
|
memcpy(data, &val, len < sizeof(mp_int_t) ? len : sizeof(mp_int_t));
|
||||||
|
} else {
|
||||||
|
while (len--) {
|
||||||
|
*data++ = val;
|
||||||
|
val >>= 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return mp_obj_str_builder_end(o);
|
return mp_obj_str_builder_end(o);
|
||||||
}
|
}
|
||||||
|
|
||||||
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_to_bytes_obj, 2, 4, int_to_bytes);
|
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_to_bytes_obj, 2, 4, int_to_bytes);
|
||||||
|
|
||||||
STATIC const mp_map_elem_t int_locals_dict_table[] = {
|
STATIC const mp_map_elem_t int_locals_dict_table[] = {
|
||||||
|
|
Loading…
Reference in New Issue