Commit 5213eb35 authored by Damien George's avatar Damien George
Browse files

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

parent 8a1cab95
......@@ -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) {
// TODO: Support long ints
// 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[0], &bufinfo);
mp_get_buffer_raise(args[1], &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);
// 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]);
......
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