Let's deal with the more familiar first and ask ourselves how someone could convert a number to its decimal representation. Converting a number to its decimal representation is to build a string consisting of its digits.
Well, we know that one can decompose a number into its digits as follows,
846 = 8*(10**2) + 4*(10**1) + 6*(10**0)
So a particular digit can be obtained as follows:
units: ( int($num / (10**0)) ) % 10
tens: ( int($num / (10**1)) ) % 10
hundreds: ( int($num / (10**2)) ) % 10
Bits are to number in binary as digits are to numbers in decimal, so converting a number to its binary representation is to build a string consisting of all its bits. The same approach can be taken.
23 = 1*(2**4) + 0*(2**3) + 1*(2**2) + 1*(2**1) + 1*(2**0)
bit 0: ( int($num / (2**0)) ) % 2
bit 1: ( int($num / (2**1)) ) % 2
bit 2: ( int($num / (2**2)) ) % 2
...
bit 7: ( int($num / (2**3)) ) % 2
The thing is, there are more efficient tools for dealing with binary.
int($i / (2**$j))
can be written as
$i >> $j
and
$k % 2
can be written as
$k & 1
We end up with
bit 0: ( $num >> 0 ) & 1
bit 1: ( $num >> 1 ) & 1
bit 2: ( $num >> 2 ) & 1
...
bit 7: ( $num >> 7 ) & 1
Now just put that in a loop, and you're done.
That said, I would just use sprintf "%08b", $num.
Based on the hint, I think they're expecting you to use the following, but this is Perl not C.
bit 0: ( $num & (1 << 0) ) >> 0 = ( $num & (1 << 0) ) ? '1' : '0'
bit 1: ( $num & (1 << 1) ) >> 1 = ( $num & (1 << 1) ) ? '1' : '0'
bit 2: ( $num & (1 << 2) ) >> 2 = ( $num & (1 << 2) ) ? '1' : '0'
...
bit 7: ( $num & (1 << 7) ) >> 7 = ( $num & (1 << 7) ) ? '1' : '0'
|