ktonon / elm-word / Word.Hex

Convert to and from strings of hexadecimal characters.

From Other to Hex


type alias CharCount =
Basics.Int

When converting from integers, the number characters in the hex string.

fromInt : CharCount -> Basics.Int -> String

Convert an integer to a string of hexadecimal characters.

fromInt 1 10
--> "a"

fromInt 8 0x42BEEF
--> "0042beef"

fromByte : Basics.Int -> String

Convert a byte to a hex string of length 2.

fromByte 0x7B
--> "7b"

fromWord : Word -> String

Convert a list of words to a string of hexadecimal characters.

import Word exposing (Word(..))

W 16 |> fromWord
--> "00000010"

D 0xDEADBEEF 0x00112233 |> fromWord
--> "deadbeef00112233"

fromByteList : List Basics.Int -> String

Convert a list of bytes to a string of hexadecimal characters.

fromByteList [ 0xde, 0xad, 0xbe, 0xef ]
--> "deadbeef"

fromWordArray : Array Word -> String

Convert an array of words to a string of hexadecimal characters.

import Word exposing (Word(..))

Word.fromUTF8 Word.Bit32 "I ❤ UTF strings!" |> fromWordArray
--> "4920e29da42055544620737472696e6773210000"

From Hex to Other

toByteList : String -> List Basics.Int

Convert a string of hexadecimal values to a list of bytes.

Fails for non-hex strings.

toByteList "not hex"
--> []

Each byte requires 2 characters, so odd length strings fail

toByteList "000"
--> []

Some passing examples

toByteList "00"
--> [ 0x00 ]

toByteList "010203040506DEADbeef"
--> [ 0x01, 0x02, 0x03, 0x04
--> , 0x05, 0x06, 0xDE, 0xAD
--> , 0xBE, 0xEF
--> ]

toWordArray : Word.Size -> String -> Array Word

Convert a string of hexadecimal values to an array of words.

import Word exposing (Word(..))

toWordArray Word.Bit32 "DEADBEEFdeadbeef" |> fromWordArray
--> "deadbeefdeadbeef"