Search code examples
crystal-lang

How to convert a hex string to bytes array in Crystal?


How can I convert a hex string to bytes array in Crystal?

Example:

87 A3 69 6E 74 01 A5 66 6C 6F 61 74 CB 3F E0 00 00 00 00 00 00 A7 62  6F 6F 6C 65 61 6E C3 A4 6E 75 6C 6C C0 A6 73 74 72 69 6E 67 A7 66 6F 6F 20 62 61 72 A5 61 72 72 61 79 92 A3 66 6F 6F A3 62 61 72 A6 6F 62 6A 65 63 74 82 A3 66 6F 6F 01 A3 62 61 7A CB 3F E0 00 00 00 00 00 00

Solution

  • Like this:

    hexstring = "87 A3 69 6E 74 01 A5 66 6C 6F 61 74 CB 3F E0 00 00 00 00 00 00 A7 62  6F 6F 6C 65 61 6E C3 A4 6E 75 6C 6C C0 A6 73 74 72 69 6E 67 A7 66 6F 6F 20 62 61 72 A5 61 72 72 61 79 92 A3 66 6F 6F A3 62 61 72 A6 6F 62 6A 65 63 74 82 A3 66 6F 6F 01 A3 62 61 7A CB 3F E0 00 00 00 00 00 00"
    bytes_array = hexstring.split.map(&.to_u8(16))
    pp bytes_array, bytes_array.class
    

    https://play.crystal-lang.org/#/r/19dh