Stream: beginners

Topic: ✔ Hex formatting of U8?


view this post on Zulip Matthieu Pizenberg (Jun 11 2024 at 18:21):

What is the simplest way to format U8 numbers into hex strings? For example, convert 255 into "ff"

view this post on Zulip Matthieu Pizenberg (Jun 11 2024 at 18:34):

I went with this since I didn’t found any obvious function from std:

hex : U8 -> Str
hex = \n ->
    high = Num.shiftRightZfBy n 4
    low = Num.bitwiseAnd n 0x0f
    Str.concat (u4Hex high) (u4Hex low)

u4Hex : U8 -> Str
u4Hex = \n ->
    when n is
        0 -> "0"
        1 -> "1"
        2 -> "2"
        3 -> "3"
        4 -> "4"
        5 -> "5"
        6 -> "6"
        7 -> "7"
        8 -> "8"
        9 -> "9"
        10 -> "a"
        11 -> "b"
        12 -> "c"
        13 -> "d"
        14 -> "e"
        15 -> "f"
        _ -> crash "n should be < 16"

view this post on Zulip Ian McLerran (Jun 11 2024 at 18:40):

u8ToHexStr : List U8 -> Str
u8ToHexStr = \bytes ->
    List.map bytes \byte ->
        b1 = byte // 16 |> \b -> if b >= 10 then b + 87 else b + 48
        b2 = byte % 16 |> \b -> if b >= 10 then b + 87 else b + 48
        Str.fromUtf8 [b1, b2] |> Result.withDefault "00"
    |> Str.joinWith ""

view this post on Zulip Matthieu Pizenberg (Jun 11 2024 at 18:48):

u4Hex = \n -> if n >= 10 then n - 10 + 'a' else n + '0'

This maybe?

view this post on Zulip Ian McLerran (Jun 11 2024 at 18:49):

Yeah, thats even better. Much clearer to the reader.
Then just: `Str.fromUtf8 [(u4Hex high), (u4Hex low)] |> Result.withDefault "00"

view this post on Zulip Notification Bot (Jun 11 2024 at 20:04):

Matthieu Pizenberg has marked this topic as resolved.


Last updated: Jul 06 2025 at 12:14 UTC