Commit 8c5632a8 authored by Damien George's avatar Damien George

py/objint: Support "big" byte-order in int.to_bytes().

parent 2bf5a947
......@@ -432,15 +432,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_fun_obj, 3, 4, int_fro
STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(int_from_bytes_obj, MP_ROM_PTR(&int_from_bytes_fun_obj));
STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) {
// TODO: Support byteorder param
// TODO: Support signed param (assumes signed=False)
(void)n_args;
if (args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little)) {
mp_not_implemented("");
}
mp_uint_t len = MP_OBJ_SMALL_INT_VALUE(args[1]);
bool big_endian = args[2] != MP_OBJ_NEW_QSTR(MP_QSTR_little);
vstr_t vstr;
vstr_init_len(&vstr, len);
......@@ -449,12 +445,13 @@ STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *args) {
#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);
mp_obj_int_to_bytes_impl(args[0], big_endian, 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);
size_t l = MIN((size_t)len, sizeof(val));
mp_binary_set_int(l, big_endian, data + (big_endian ? (len - l) : 0), val);
}
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
......
......@@ -8,3 +8,9 @@ print(int.from_bytes(b"\x00\x01\0\0\0\0\0\0", "little"))
# check that extra zero bytes don't change the internal int value
print(int.from_bytes(bytes(20), "little") == 0)
print(int.from_bytes(b"\x01" + bytes(20), "little") == 1)
# big-endian conversion
print((10).to_bytes(1, "big"))
print((100).to_bytes(10, "big"))
print(int.from_bytes(b"\0\0\0\0\0\0\0\0\0\x01", "big"))
print(int.from_bytes(b"\x01\0", "big"))
print((2**64).to_bytes(9, "little"))
print((2**64).to_bytes(9, "big"))
b = bytes(range(20))
......@@ -7,6 +8,7 @@ ib = int.from_bytes(b, "big")
print(il)
print(ib)
print(il.to_bytes(20, "little"))
print(ib.to_bytes(20, "big"))
# check that extra zero bytes don't change the internal int value
print(int.from_bytes(b + bytes(10), "little") == int.from_bytes(b, "little"))
try:
print((10).to_bytes(1, "big"))
except Exception as e:
print(type(e))
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment