in reply to Bitwise operators

Your original question deals with bitwise operators as a method of examining the bits behind a number. ...then we started talking about unpack() instead, which works, but may not satisfy the requirements of what you're trying to learn.

I implemented a solution just now using the & operator (which is a bit-wise operator), with $number & $bit_value, iterating over the values of individual bits. I don't want to ruin your homework learning experience, so I guess I'll just try to describe the method:

Start by setting $bit_value to 1. This represents the value of the least significant bit. Then take $number & $bit_value. If you get a non-zero value, that bit is 'set'. Keep track of it. Then repeat the process for $bit_value being equal to 2, then to 4, then to 8, 16, 32, and so on. Each time keep track of whether the specific bit is set.

This will give you a list of set or unset bits, in order of least significant to most significant. Once you've worked through it yourself with those hints, try posting some code, and I'll show you a comparison with how I did it.


Dave

Replies are listed 'Best First'.
Re^2: Bitwise operators
by thevoid (Scribe) on Dec 24, 2006 at 22:15 UTC
    Great, thanks Dave - will have a go tomorrow : )

      Ok, I've seen what you posted lower down in this thread, and wanted to follow up to my earlier promise to offer some code.

      The following solution will work for any integer, whether it requires 4 bits or 32 to represent it.

      use strict; use warnings; my $number = 75; my $bitval = 1; my $bits = ''; while ( $bitval <= $number ) { my $bit = $number & $bitval ? 1 : 0; $bits = $bit . $bits; $bitval *= 2; } print $bits, "\n";

      $bitval contains the mask value, and is incremente by times two after each iteration. That makes the masks 1, 2, 4, 8, 16, 32.... etc. (look familiar?). The ... ? ... : ... (ternary operator) serves to turn a bit value into just a zero or one. The rest I think you'll figure out as you look at it.


      Dave

        That's cool, thanks again Dave

        Really glad I found this site, working through it on my own would have been a nightmare...