I need a function which will print out the binary representation of a read file like the xxd program in unix, but I want to make my own. Hexidecimal works just fine with %x but there is no built in format for binary. Anyone know how to do this?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
I usually do not believe in answering these sorts of questions with full code implementations, however I was handed this bit of code many years ago and I feel obligated to pass it on. I have removed all the comments except for the usage, so you can try to figure out how it works yourself.
Code base 16
Output base 16 (Excerpt from first 512 bytes* of a flash video)
I assume you already know how to tell the size of a file and read a file in binary mode, so I will leave that out of the discussion. Depending on your terminal width you may need to adjust the variable:
width
-- the code is currently designed for 80 character terminals.I am also assuming that when you mentioned
xxd
in conjunction with "binary" you meant non-text as opposed to base 2. If you want base 2, setwidth
to 6 and replaceprintf ("%02x ", (unsigned char) str [j]);
with this:The required change is pretty simple, you just need to individually shift all 8 bits of your octet and mask off all but the least-significant bit. Remember to do this in an order that seems counter-intuitive at first, since we print left-to-right.
Output base 2 (Excerpt from first 512 bytes* of a flash video)
*For the sake of simplicity, let us pretend that a byte is always 8-bits.
Depending on the language, assuming you have bitwise operations, which lets you act on each bit of a variable, you can do the following. Read the file into a buffer, or a line, if encoding is needed, force it to extended ASCII (8 bit/ 1 byte character) now, when you get the buffer, you loop from 7 to 0 and using the and bitwise and a shift to check each bit value, let me give an example in C: