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
To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2];
Byte to Hexadecimal. The bytes are 8 bit signed integers in Java. Therefore, we need to convert each 4-bit segment to hex separately and concatenate them. Consequently, we'll get two hexadecimal characters after conversion.
Converting between hex and binary is easy, because each digit of a hexadecimal number "maps" to four bits (a bit being an individual binary digit) of a binary value. So a byte -- eight binary digits -- can always be represented by two hexadecimal digits.
hex() function in Python. hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With