Skip to content

Commit fcdb239

Browse files
committed
py: Make int.to_bytes work on big endian machine.
Partly addresses issue adafruit#856.
1 parent a9bcd51 commit fcdb239

1 file changed

Lines changed: 15 additions & 7 deletions

File tree

py/objint.c

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -327,20 +327,28 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_fun_obj, 2, 3, int_fro
327327
STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(int_from_bytes_obj, (const mp_obj_t)&int_from_bytes_fun_obj);
328328

329329
STATIC mp_obj_t int_to_bytes(mp_uint_t n_args, const mp_obj_t *args) {
330+
// TODO: Support long ints
331+
// TODO: Support byteorder param (assumes 'little')
332+
// TODO: Support signed param (assumes signed=False)
333+
330334
mp_int_t val = mp_obj_int_get_checked(args[0]);
335+
mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[1]);
331336

332-
uint len = MP_OBJ_SMALL_INT_VALUE(args[1]);
333337
byte *data;
334-
335-
// TODO: Support long ints
336-
// TODO: Support byteorder param
337-
// TODO: Support signed param
338338
mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
339339
memset(data, 0, len);
340-
memcpy(data, &val, len < sizeof(mp_int_t) ? len : sizeof(mp_int_t));
340+
341+
if (MP_ENDIANNESS_LITTLE) {
342+
memcpy(data, &val, len < sizeof(mp_int_t) ? len : sizeof(mp_int_t));
343+
} else {
344+
while (len--) {
345+
*data++ = val;
346+
val >>= 8;
347+
}
348+
}
349+
341350
return mp_obj_str_builder_end(o);
342351
}
343-
344352
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_to_bytes_obj, 2, 4, int_to_bytes);
345353

346354
STATIC const mp_map_elem_t int_locals_dict_table[] = {

0 commit comments

Comments
 (0)