Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: binary conversion

by ikegami (Patriarch)
on Dec 12, 2011 at 18:31 UTC ( [id://943152]=note: print w/replies, xml ) Need Help??


in reply to binary conversion

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'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://943152]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (9)
As of 2024-04-18 16:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found