alih110 has asked for the wisdom of the Perl Monks concerning the following question:
I have a loop from 0 to 127. I need to do the following in perl =>
1. convert this decimal number (0 to 127) into a binary string of 8 bits
2. split this binary number into 2 bits each like "dd cc bb aa"
3. Check if any 2 consecutive bits is 0 i.e. either dd or cc or bb or aa is equal to zero and update a counter if they are.
I tried the following code but it is not working =>
The problem with this code is that it increments the count even if binary value = 01 01 10 01 i.e. bb = 10 and aa = 01 I want it to increment the count only if aa || bb || cc || dd is zero It would have been easier if I could have somehow split the 8 bit binary number into 2 bits each in the format of dd cc bb aa However I don't know how to do that. Will unpack help here? Anywayz would be greatful if someone can help me with this. At the end of the loop the counter should have value 101 and right now it reaches count 107. Thanks.------------------------------- for ($v = 0; $v < 128; $v++) { $bin_num = sprintf("%0b", $v); # This will give me the binary num +ber if ($v < 64) { $cnt++; # Because uptil value 63 "dd" is always going to be +zero } else { if ($bin_num =~ /00/) { print "\n Coming here if string 00 found for value $bin_nu +m \n"; $cnt++; } else { print "\n Coming here if string 00 NOT found for value $bi +n_num \n"; } } -------------------------------
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: binary string
by toolic (Bishop) on Jan 15, 2009 at 14:10 UTC | |
Re: binary string
by Corion (Patriarch) on Jan 15, 2009 at 13:56 UTC | |
Re: binary string
by BrowserUk (Patriarch) on Jan 15, 2009 at 14:15 UTC | |
Re: binary string
by johngg (Canon) on Jan 15, 2009 at 14:48 UTC | |
Re: binary string
by gone2015 (Deacon) on Jan 15, 2009 at 16:16 UTC | |
Re: binary string
by borisz (Canon) on Jan 15, 2009 at 15:28 UTC | |
Re: binary string
by NetWallah (Canon) on Jan 15, 2009 at 21:14 UTC | |
Re: binary string
by rir (Vicar) on Jan 15, 2009 at 19:16 UTC |
Back to
Seekers of Perl Wisdom