Hex
Encode and decode hexadecimal strings. Useful for representing binary data, hash digests, and color codes.
import Encoding.Hex
Encoding
Hex.encode
String -> String
Encode a string to lowercase hexadecimal. Each byte becomes two hex characters.
hex = Hex.encode "Hello"
# "48656c6c6f"
# Binary data
bytes = Hex.encode "\x00\xff\x10"
# "00ff10"
Decoding
Hex.decode
String -> String
Decode a hexadecimal string back to the original bytes.
Returns an empty string for invalid input.
decoded = Hex.decode "48656c6c6f"
# "Hello"
# Case insensitive
decoded = Hex.decode "48656C6C6F"
# "Hello"
Validation
Hex.valid?
String -> Bool
Check if a string is valid hexadecimal. Must have even length and
contain only characters 0-9, a-f, A-F.
Hex.valid? "48656c6c6f" # true
Hex.valid? "DEADBEEF" # true
Hex.valid? "123" # false (odd length)
Hex.valid? "hello" # false (invalid chars)
Common Uses
Hex encoding is commonly used for:
- Hash digests (SHA256, MD5, etc.)
- Color codes (#ff5500)
- MAC addresses (00:1A:2B:3C:4D:5E)
- Binary data in text formats