How can I convert a binary file to a base 2 repres

2019-06-03 15:01发布

问题:

I can convert a binary file to an ASCII base 64 representation in a way such as the following:

base64 piglet_squid.jpg > piglet_squid.txt

A small segment of the resulting file could be something like the following:

LY61c8T1LeF+GsbJ2FhEjnNW0NoXFS0qi2MEKKyPErh13jSWFU+Xp8uRxu6Cqxzcn8cfCJxrYrwj
wx9PYNy+ZvXfUzHmsH7XKNBaTULLsXAHtXqbmtSze8knfeHKL0+a8R9qn13iniFuwilbK8x9K+9d
PMUXGvsxxX2sufZnxO9rrTK5221Bk9jWppTa8T8R3Ok6e3/hjox715M+KabSrb8M0jejC3bg6/Fe

How could I convert that same file to a base 2 representation? A small segment of the resulting file could be something like the following:

0101000111001011101010001010010110101001010010110111110101001000101010010100
0001010101001010101010010010011010101011101010110101001101110000000110011010
0100111010111111010100100010100001011010101010111010111010000101010010110101

My preference is to do this using very standard Linux utilities.

回答1:

(echo obase=2; hexdump -ve'/1 "%u\n"' piglet_squid.jpg)|bc|xargs printf %08i|fold -w64

This line converts the file piglet_squid.jpg to a base 2 representation on standard output; the line length can be altered by specifying another width with fold -w.