Home > OS >  Looking for convenient way of converting space separated ASCII numbers to letters in Shell
Looking for convenient way of converting space separated ASCII numbers to letters in Shell

Time:07-09

I want to convert 104 101 108 108 111 to hello string in Shell without using any external tool. What would be the convenient way to do this?

CodePudding user response:

There a function that'll help:

chr() {
    printf "\x$(printf "%x" "$1")"
}
chr 65    # => A

CodePudding user response:

This should work on any POSIX shell:

#!/bin/sh                                                                                                                                                                                                                                        
numbers="104 101 108 108 111"
# Rely on word splitting here to break up the string                                                                                                                                                                                             
printf "$(printf '\%o' $numbers)\n"

The inner printf converts each decimal number to a base-8 octal one with a leading backslash, which the outer printf then displays as the corresponding character. Plus a newline for neatness.

  • Related