Skip to content

Commit 7203b58

Browse files
committed
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'
1 parent b4c65c2 commit 7203b58

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

extmod/modubinascii.c

+11-2
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,18 @@
3737
mp_obj_t mod_binascii_hexlify(mp_uint_t n_args, const mp_obj_t *args) {
3838
// Second argument is for an extension to allow a separator to be used
3939
// between values.
40-
(void)n_args;
40+
const char *sep = NULL;
4141
mp_buffer_info_t bufinfo;
4242
mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
4343

4444
vstr_t vstr;
45-
vstr_init_len(&vstr, bufinfo.len * 2);
45+
size_t out_len = bufinfo.len * 2;
46+
if (n_args > 1) {
47+
// 1-char separator between hex numbers
48+
out_len += bufinfo.len - 1;
49+
sep = mp_obj_str_get_str(args[1]);
50+
}
51+
vstr_init_len(&vstr, out_len);
4652
byte *in = bufinfo.buf, *out = (byte*)vstr.buf;
4753
for (mp_uint_t i = bufinfo.len; i--;) {
4854
byte d = (*in >> 4);
@@ -55,6 +61,9 @@ mp_obj_t mod_binascii_hexlify(mp_uint_t n_args, const mp_obj_t *args) {
5561
d += 'a' - '9' - 1;
5662
}
5763
*out++ = d + '0';
64+
if (sep != NULL && i != 0) {
65+
*out++ = *sep;
66+
}
5867
}
5968
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
6069
}

0 commit comments

Comments
 (0)