Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string to list of hexadecimal of each byte (Raku)

Tags:

raku

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

like image 428
Tinmarino Avatar asked Mar 25 '20 22:03

Tinmarino


People also ask

How do you convert hexadecimal strings to bytes?

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];

How many hex is 4 bytes?

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.

How many bytes is a hexadecimal?

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.

How do you declare a hex array in Python?

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.


1 Answers

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.

like image 113
Jonathan Worthington Avatar answered Sep 25 '22 22:09

Jonathan Worthington