Solved Bash with echo convert word to bin, hex and oct?

conversion:
word="hello world"

to binary:
results="01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100"

to hexadecimal:
results="0x68 0x65 0x6c 0x6c 0x6f 0x20 0x77 0x6f 0x72 0x6c 0x64"

to octal:
results="150 145 154 154 157 40 167 157 162 154 144"

example code:
Code:
str="hello world"
for ((z=0; z<${#str}; z+=2))
    do
        echo -e "%s"$((${str:$z:1}&1))) # BIN
        echo -e "%02x"${str:$z:2}  # HEX
        echo -e "%3o"${str:$z:2} # OCT
done

Thanks for help
 
ok, if it doesn't work with echo and sed or awk, does anyone know how it works with printf?

I have searched in the net but found no way encrypt word to binary and decrypt back.

I know python is the easiest way, but in last time so many libraries have been changed and 2.7 was before always more sympathetic for me.
 
if you can do hex binary is easy
just sed 4 bits to one hex digit and viceversa
or
Code:
#!/bin/sh
b2h()
{
case $1 in
 "0000") echo 0;;
 "0001") echo 1;;
 "0010") echo 2;;
 "0011") echo 3;;
 "0100") echo 4;;
 "0101") echo 5;;
 "0110") echo 6;;
 "0111") echo 7;;
 "1000") echo 8;;
 "1001") echo 9;;
 "1010") echo A;;
 "1011") echo B;;
 "1100") echo C;;
 "1101") echo D;;
 "1110") echo E;;
 "1111") echo F;;
esac;
}
results="01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100"
for byte in $results
do
l=${byte#????}
h=${byte%????}
eval hh=$(b2h $h)
eval hl=$(b2h $l)
echo -n "0x$hh$hl "
done
echo
 
Code:
#!/usr/local/bin/bash
charCode()
{
local i j c
[ "$1" = "'" ] && echo 0x27 && return
for i in  1 2 3 4 5 6 7 8
 do
 for j in 0 1 2 3 4 5 6 7 8 9 a b c d e f
  do
   [ "$i$j" == 27 ] && continue
   eval c=\'$(echo -e \\x$i$j)\'
   [ "$c" = "$1" ] && echo 0x$i$j && return
  done
 done
}

charCode A
charCode c
charCode @
charCode "'"
charCode '"'
you can make a faster one using binary search not linear like this
 
Back
Top