#!/usr/bin/perl # # bit_checker # # Checks to make sure the file only contains valid bits. # Only values of 0 and 1 are considered valid for bits. # # usage: bit_checker [<file> [...] ] # # Exit code 0 if no errors. # Nonzero exit code on error. # # Assumes an 8-bit per byte system # # Inspired by http://thedailywtf.com/Articles/Some-Crazy-Reason.aspx # use strict; use warnings; sub process { my ($fh, $name) = @_; my $error = 0; my $offset = 0; local $/ = \(64*1024); while (my $blk = <$fh>) { for my $byte_idx ( 0 .. length($blk)-1 ) { my $byte = ord(substr($blk, $byte_idx, 1)); for my $bit_idx ( reverse 0 .. 7 ) { my $bit = ( $byte >> $bit_idx ) & 1; if ($bit != 0 && $bit != 1) { $error = 1; warn("Found bad bit ($bit) in $name" ." at pos ".( $offset+$byte_idx ).":$bit_idx" .\n"); } } } $offset += length($blk); } return $error; } { my $error = 0; if (@ARGV) { for my $qfn (@ARGV) { # Raw stream without disabling buffering. open(my $fh, '<:unix:perlio', $qfn) or die("Can't open \"$qfn\": $!\n"); $error = process($fh, "file \"$qfn\"") || $error; } } else { binmode(*STDIN); $error = process(*STDIN, 'STDIN'); } exit($error); }

Getting 100% test coverage is going to be hard...


In reply to Bit Checker by ikegami

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.