diff options
author | Paul Sokolovsky <pfalcon@users.sourceforge.net> | 2015-12-26 02:12:15 +0200 |
---|---|---|
committer | Paul Sokolovsky <pfalcon@users.sourceforge.net> | 2015-12-26 02:15:56 +0200 |
commit | 7203b58e876cffe9bb7246e17c206e7b4280f701 (patch) | |
tree | 5bd7928fa73e436e520d262d34bdec3532491909 | |
parent | b4c65c253fbd8d020df45ae585c9d1b97ef361a6 (diff) | |
download | micropython-7203b58e876cffe9bb7246e17c206e7b4280f701.tar.gz micropython-7203b58e876cffe9bb7246e17c206e7b4280f701.zip |
extmod/modubinascii: Add "separator" argument to hexlify().
This is extension to CPython, it allows to easily produce human-readable
hex dump:
>>> ubinascii.hexlify(b"\xaa\x55\xaa\x55", b" ")
b'aa 55 aa 55'
-rw-r--r-- | extmod/modubinascii.c | 13 |
1 files changed, 11 insertions, 2 deletions
diff --git a/extmod/modubinascii.c b/extmod/modubinascii.c index 08562372fc..12cd266870 100644 --- a/extmod/modubinascii.c +++ b/extmod/modubinascii.c @@ -37,12 +37,18 @@ mp_obj_t mod_binascii_hexlify(mp_uint_t n_args, const mp_obj_t *args) { // Second argument is for an extension to allow a separator to be used // between values. - (void)n_args; + const char *sep = NULL; mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); vstr_t vstr; - vstr_init_len(&vstr, bufinfo.len * 2); + size_t out_len = bufinfo.len * 2; + if (n_args > 1) { + // 1-char separator between hex numbers + out_len += bufinfo.len - 1; + sep = mp_obj_str_get_str(args[1]); + } + vstr_init_len(&vstr, out_len); byte *in = bufinfo.buf, *out = (byte*)vstr.buf; for (mp_uint_t i = bufinfo.len; i--;) { byte d = (*in >> 4); @@ -55,6 +61,9 @@ mp_obj_t mod_binascii_hexlify(mp_uint_t n_args, const mp_obj_t *args) { d += 'a' - '9' - 1; } *out++ = d + '0'; + if (sep != NULL && i != 0) { + *out++ = *sep; + } } return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } |