function hex() {
    printf "%%%02x\n" "'$1"
}

hex -   # Outputs %2d
hex _   # Outputs %5f
hex .   # Outputs %2e