5

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

Tinmarino
  • 3,693
  • 24
  • 33

1 Answers1

8

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.

Jonathan Worthington
  • 29,104
  • 2
  • 97
  • 136
  • I wonder whether it would make sense to have a `.base` method on `Blob`. – Elizabeth Mattijsen Mar 25 '20 at 22:57
  • 2
    @ElizabethMattijsen For debug you can just `gist` the `Buf` anyway; otherwise, every time I've done this in a practical context there's usually many other formatting decisions about line splitting, wanting to have a non-hex interpretation to the side, etc. – Jonathan Worthington Mar 25 '20 at 23:12