Reputation: 4041
FAQ: In Raku, how to convert a string to the list of its bytes hexadecimal from (i.e. hex decoder)
Currently, I have:
say "I ❤ 🦋".encode.list.map(*.base(16)); # (49 20 E2 9D A4 20 F0 9F A6 8B)
Which is 4 operations
Upvotes: 5
Views: 346
Reputation: 29454
The way in the question is pretty much fine. Since map
will coerce to a list
anyway, however, one can drop the explicit .list
coercion, giving:
say "I ❤ 🦋".encode.map(*.base(16));
Since .base
is a pure operation, it's also safe for use with the >>
hyper-operator, which will also listify:
say "I ❤ 🦋".encode>>.base(16);
If I'm nitpicking a bit, note that "convert a string to the list of its bytes" is underspecified without talking about an encoding. The default is UTF-8, so encode
will convert the string into that. In Raku, the byte-level representation of strings in memory is not a defined aspect of the language, and strings are an opaque data type. An implementation is free to pick whatever underlying representation it sees fit (MoarVM has at least 3 ways to model a string internally), however as the language user you don't ever get to see that.
Upvotes: 8