py: Make int.from_bytes a classmethod; support arbitrary length buf.

This commit is contained in:
Damien George 2014-04-13 12:24:13 +01:00
parent 8a1cab952f
commit 5213eb35b5

View file

@ -265,18 +265,27 @@ mp_obj_t mp_obj_int_binary_op_extra_cases(int op, mp_obj_t lhs_in, mp_obj_t rhs_
return MP_OBJ_NULL;
}
// this is a classmethod
STATIC mp_obj_t int_from_bytes(uint n_args, const mp_obj_t *args) {
buffer_info_t bufinfo;
mp_get_buffer_raise(args[0], &bufinfo);
assert(bufinfo.len >= sizeof(machine_int_t));
// TODO: Support long ints
// TODO: Support byteorder param
// TODO: Support signed param
return mp_obj_new_int_from_uint(*(machine_uint_t*)bufinfo.buf);
// TODO: Support byteorder param (assumes 'little' at the moment)
// TODO: Support signed param (assumes signed=False at the moment)
// get the buffer info
buffer_info_t bufinfo;
mp_get_buffer_raise(args[1], &bufinfo);
// convert the bytes to an integer
machine_uint_t value = 0;
for (uint i = 0; i < bufinfo.len; i++) {
value += ((byte*)bufinfo.buf)[i];
}
return mp_obj_new_int_from_uint(value);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_obj, 1, 3, int_from_bytes);
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(int_from_bytes_fun_obj, 2, 3, int_from_bytes);
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(uint n_args, const mp_obj_t *args) {
machine_int_t val = mp_obj_int_get_checked(args[0]);