split a string and convert to binary

Hi All,
Iam new to unix scripting and I want a split a string into 4 characters each, leaving the last two characters and convert the splitted values into binary.
For example:
string='ffd80012ffe20000ffebfffeffea0007fff0ffd70014fff1fff0fff0fff201'
this should split as
ffd8
0012
ffe2
.
.
.
fff2
leaving 01 and each value should be converted to binary
Please provide a shell script for this.
Thanks inadvance

Assuming the values in string are hexanumbers ..

$ cat filename
#!/bin/ksh
string='ffd80012ffe20000ffebfffeffea0007fff0ffd70014fff1fff0fff0fff201'
echo $string | fold -w 4 | sed '$d' > hexanumbers.txt
for i in `cat hexanumbers.txt | awk '{ print "16#"$0}'`
do
typeset -i10 i
echo $i >> decimals_list.txt
done
for i in `cat decimals_list.txt`
do
        echo "obase=2;$i" | bc
done
rm decimals_list.txt
$ ksh filename
1111111111011000
10010
1111111111100010
0
1111111111101011
.......
.......

---------- Post updated at 01:26 PM ---------- Previous update was at 01:25 PM ----------

A simpler, more efficient solution utilizing the same basic utilities:

echo $string | fold -w4 | sed '$d; y/abcdef/ABCDEF/; 1s/^/obase=2; ibase=16; /' | bc

Regards,
Alister

1 Like

thanx alister and jayan for the solution.

Here is a nice little solution just using the bash shell:

a=( 0000 0001 0010 0011 0100 0101 0110 0111
    1000 1001 1010 1011 1100 1101 1110 1111 )
 
string='ffd80012ffe20000ffebfffeffea0007fff0ffd70014fff1fff0fff0fff201'
 
for((i=0; $i <${#string}; i++))
do
    printf ${a[16#${string:i:1}]}
    [ $((i%4)) -eq 3 ] && echo
done
echo

Output:

1111111111011000
0000000000010010
1111111111100010
0000000000000000
1111111111101011
1111111111111110
1111111111101010
0000000000000111
1111111111110000
1111111111010111
0000000000010100
1111111111110001
1111111111110000
1111111111110000
1111111111110010
00000001

And here's one using Perl:

$

$ echo $str
ffd80012ffe20000ffebfffeffea0007fff0ffd70014fff1fff0fff0fff201
$
$
$ echo $str | perl -lne 's/..$//; print for map {unpack("B16",pack("H4",$_))} unpack("(A4)*",$_)'
1111111111011000
0000000000010010
1111111111100010
0000000000000000
1111111111101011
1111111111111110
1111111111101010
0000000000000111
1111111111110000
1111111111010111
0000000000010100
1111111111110001
1111111111110000
1111111111110000
1111111111110010
$
$

tyler_durden