Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

padding zeros to binary numbers using shell scripting

How to pad zero to binary numbers using shell script.

binary.txt

1010011100010001010111001101111
0
10110000000101000000000000001
10100000011
1000000100
1111111111111111
11111111111111110000000000000000
11111111111111110000000000000000
11111111111111110000000000000000
11111111111111110000000000000000
11111111111111110000000000000000
11111111111111110000000000000000
11111111111111110000000000000000
11111111111111110000000000000000
11111111111111110000000000000000
11111111111111110000000000000000

when i do the following

printf "%032s\n" $(<binary.txt)

I get a white space.

  1010011100010001010111001101111
                                0
    10110000000101000000000000001
                      10100000011
                       1000000100
                 1111111111111111
 11111111111111110000000000000000
 11111111111111110000000000000000
 11111111111111110000000000000000

But I need zero's appended. Any input is appreciated. thanks,

Updated:

binary.txt is my input file and has the following contents.

1010011100010001010111001101111
0
10110000000101000000000000001
10100000011
1000000100
1111111111111111
11111111111111110000000000000000
11111111111111110000000000000000

while running the following command in the command line it works fine.

   printf "%032s\n" $(<binary.txt) | tr ' ' '0' >> t1.mif

But when i try to do the same using a script below , it gives me wrong values. Any suggestions.

#!/bin/bash
FILE=binary.txt
while read line;do
    printf "%032s\n" $line | tr ' ' '0' >> t1.mif
done < $FILE

thanks

like image 817
user2532296 Avatar asked Mar 04 '26 09:03

user2532296


1 Answers

You can use tr to replace the spaces you get with zeroes:

printf "%032s\n" $(<binary.txt) | tr ' ' '0'
like image 77
julienc Avatar answered Mar 06 '26 01:03

julienc