Gerard has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, any suggestions greatly appreciated.
I know how to get bytes from a file, and write them to another file, using something like the below, but what I want to do is some processing on certain bits before writing them back. Any ideas on how to go about this? I am running this script on Win 32, perl 5.6
open (IN, "< ./someinputfile") || die $!; open (OUT, "> ./someoutputfile") || die $!; binmode IN; binmode OUT; my $read = 1; my $result; while($read > 0){ $read = read IN,$result,1; #do some processing and checking here. #convert the bits to bytes print OUT $result; }
How do I convert the byte stored in $result to the 0's and 1's that it represents? Well there is a bit more to it than that, but that would be a good place to start. (Haven't done much file processing in the past).

Thanks in advance,
Gerard

Replies are listed 'Best First'.
Re: Bytes to bits
by dragonchild (Archbishop) on Aug 14, 2003 at 14:59 UTC
    Take a look at vec. Also, the &, !, |, ^, <<, and >> operators are your friend. (Bit-manipulating and -shifting operators). (Those logic operators are just 1 character. & vs. &&)

    ------
    We are the carpenters and bricklayers of the Information Age.

    The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      ++ to both of you. vec() seems to do exactly what I want. Now I can play.

      Much appreciated

      Regards,
      Gerard
Re: Bytes to bits
by Abigail-II (Bishop) on Aug 14, 2003 at 14:59 UTC
    Well, that depends on how you want to represent those bits. Remember that $result is a one character string, containing 8 bits already.

    You might want to lookup the working of vec, that may very well do what you want to do.

    Abigail

Re: Bytes to bits
by bfish (Novice) on Aug 14, 2003 at 16:22 UTC

    I think that the answer to your question is easier than you think. $result is in the 0's and 1's format you desire already. The question, then, is how to manipulate that data!

    Are you familiar with masks? If not, then you need to read more about binary math. If you are familiar with masks, then the following will be straightforward. Suppose you want to find out whether the value in the 4th position from the right is set and then do something like set the value in the second position from the right. The code to do this in PERL is below:

    I hope this answers your question!

Re: Bytes to bits
by NetWallah (Canon) on Aug 14, 2003 at 17:56 UTC
    I'm surprised no one has suggested the pack() and unpack() functions - unpack() can extract bits, and assign them to separate variables, which you can re-assemble with pack.