Print a file in binary form (1 and 0)
Question
In the context of a GZip decoder I need a unix tool or a C solution to print my compressed gzip file on my screen in a binary form. What I exactly need is hexdump able to print in binary instead of octal,decimal or hexadecimal.
I am pretty sure this tool exists but I can't find it :-(
EDIT I guess such editor is hard to find because the use case must not be frequent. In my case I have very small files and need for debug purpose to search for binary "patterns" such as 10010011 that may cross several bytes
Solution
perl -ne 'print unpack(B8,$_),$/for split//' FILE
or to have 8 elements in a line
perl -ne 'print unpack(B8,$_),++$i%8?" ":"\n"for split//;END{print"\n"}'
without linebreaks
perl -ne 'print unpack(B8,$_)for split//' FILE
OTHER TIPS
Because Manuel told me to repost, I completed the commentary that I wrote last time, and here is the call:
od -t x1 FILE | sed 'h;x;s:^\(........\).*:\1:;x;s:^........::;s:0:0000:g;s:1:0001:g;s:2:0010:g;s:3:0011:g;s:4:0100:g;s:5:0101:g;s:6:0110:g;s:7:0111:g;s:8:1000:g;s:9:1001:g;s:a:1010:g;s:b:1011:g;s:c:1100:g;s:d:1101:g;s:e:1110:g;s:f:1111:g;H;x;s:\n::'
your compiler could support this utility function ltoa
char *ltoa( long value, char * buffer, int radix );
that could simplify the display with radix = 2
From another answer I made (that I unfortunately can't find right now) I have this function to print an int
as binary digits:
void print_bin(int n)
{
for (int i = sizeof(n) * 8 - 1; i >= 0; i--)
printf("%d", (int) ((n >> i) & 1));
}
You can read the file as integers and use this function to print the values as binary digits.
od -t x1 FILE | sed 's:0:0000:g;s:1:0001:g;\
s:2:0010:g;s:3:0011;
...[replace every hex-digit up to F with the bin representation] '
Just write a little program:
#include <stdio.h>
void binarywrite (unsigned char c)
{
int i = 0;
for (i = 0; i < 8; i++)
{
printf("%1d",(c>>(7-i)) & 1 );
}
printf(" ");
}
int main(int argc, char* argv[])
{
char c = 0;
if(argc >=2)
{
char* pfilename = argv[1];
FILE *fp;
fp = fopen(pfilename,"rb");
char ch;
while((ch = getc(fp)) != EOF)
{
binarywrite(ch);
}
fclose(fp);
}
return 0;
}
And you can use it as './binarywite filename'
xxd (which usually comes with vim) can convert to binary representation directly:
xxd -b FILE
To cut off the formatting of the output, a bit of awk can be appended so you get a clean stream of zeros and ones only:
xxd -b FILE | \
awk '{ for (i=0; i<NF; i=i+1)
{ if ($i ~ /^[01][01][01][01][01][01][01][01]$/) printf $i }
}; END { print "" }
'