how to "decdump" a string in bash?

784 views Asked by At

I need to convert a string into a sequence of decimal ascii code using bash command.

example: for the string 'abc' the desired output would be 979899
where a=97, b=98 and c=99 in ascii decimal code.

I was able to achieve this with ascii hex code using xxd.

printf '%s' 'abc' | xxd -p

which gives me the result: 616263
where a=61, b=62 and c=63 in ascii hexadecimal code.

Is there an equivalent to xxd that gives the result in ascii decimal code instead of ascii hex code?

3

There are 3 answers

1
tshiono On BEST ANSWER

If you don't mind the results are merged into a line, please try the following:

echo -n "abc" | xxd -p -c 1 |
while read -r line; do
    echo -n "$(( 16#$line ))"
done

Result:

979899
0
user1934428 On
str=abc
printf '%s' $str | od -An -tu1

The -An gets rid of the address line, which od normally outputs, and the -tu1 treats each input byte as unsigned integer. Note that it assumes that one character is one byte, so it won't work with Unicode, JIS or the like.

If you really don't want spaces in the result, pipe it further into tr -d ' '.

1
Ross Jacobs On

Unicode Solution

What makes this problem annoying is that you have to pipeline characters when converting from hex to decimal. So you can't do a simple conversion from char to hex to dec as some characters hex representations are longer than others.

Both of these solutions are compatible with unicode and use a character's code point. In both solutions, a newline is chosen as separator for clarity; change this to '' for no separator.

Bash

sep='\n'
charAry=($(printf 'abc' | grep -o .))
for i in "${charAry[@]}"; do
  printf "%d$sep" "'$i"
done && echo
97
98
99
127926

Python (in Bash)

Here, we use a list comprehension to convert every character to a decimal number (ord), join it as a string and print it. sys.stdin.read() allows us to use Python inline to get input from a pipe. If you replace input with your intended string, this solution is then cross-platform.

printf '%s' 'abc' | python -c "
import sys
input = sys.stdin.read()
sep = '\n'
print(sep.join([str(ord(i)) for i in input]))"
97
98
99
127926

Edit: If all you care about is using hex regardless of encoding, use @user1934428's answer