Guest User

Untitled

a guest
Jan 18th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. // see: see the physical bits in a file
  2. // usage: see [filename]
  3. // sort of like the `od' command, but only supports binary output
  4.  
  5. // $ echo foobar > foo.txt; see foo.txt
  6. // 01100110 01101111 01101111 01100010
  7. // 01100001 01110010 00001010
  8. // $
  9.  
  10. // bugs:
  11. //   - assumes big-endianness of machine
  12. //   - only allows one file to be seen at a time
  13. //   - no command line options
  14. //   - generally untested
  15.  
  16. #include <stdio.h>
  17.  
  18. int main(int argc, char **argv)
  19. {
  20.         FILE *fp;
  21.         if (argc > 1)
  22.         {
  23.                 if ((fp = fopen(argv[1], "r")) == NULL)
  24.                 {
  25.                         fprintf(stderr, "see: could not open file `%s': ");
  26.                         perror(NULL);
  27.                         return -1;
  28.                 }
  29.         }
  30.         else
  31.                 fp = stdin;
  32.  
  33.         unsigned currbyte;
  34.         signed currbit;
  35.  
  36.         int col = 0;
  37.         int maxcols = 4;
  38.  
  39.         while ((currbyte = fgetc(fp)) != EOF)
  40.         {
  41.                 for (currbit = 7; currbit >= 0; currbit--)
  42.                 {
  43.                         if ( (currbyte >> currbit) & 1 )
  44.                                 putchar('1');
  45.                         else
  46.                                 putchar('0');
  47.                 }
  48.                 putchar(' ');
  49.  
  50.                 if (++col == maxcols)
  51.                 {
  52.                         col = 0;
  53.                         putchar('\n');
  54.                 }
  55.         }
  56.  
  57.         if (col > 0)
  58.                 putchar('\n');
  59.  
  60.         return 0;
  61. }
Add Comment
Please, Sign In to add comment