Perl Monk, Perl Meditation  
PerlMonks 
Re: Decimal to Binary using Bitwise and operatorby RMGir (Prior) 
on Jul 15, 2009 at 19:12 UTC ( #780444=note: print w/replies, xml )  Need Help?? 
I'm not going to give you the program, but I'll give you some
hints that may help you figure out the answer.
In the binary representation of a number, a value is made up of a certain number of bits. For values less than 256, as in your question, this requires 8 bits (also known as 1 byte). Binary numbers are just like our usual decimal numbers  all that changes is the number base. 2 for binary, 10 for decimal. So, in decimal, 250 is 2*100 + 5*10 + 0*1, while the same number in binary is 11111010 (1 * 128 + 1*64 + 1*32 + 1*16 + 1*8 + 0*4 + 1*2 + 0*1). The bitwise and operator & works on the bits that make up a number. So 250&32 is going to return 32, because that bit is on in 250, but 250&1 is going to return 0, because the 1's bit is not on in 250. So, by using & with masks 1, 2, 4, 8, 16, 32, 64, and 128, you should be able to build up the binary representation of your input number... As a bonus feature, perl's printf implementation allows the "%b" specifier to be used, so you can use that to quickly implement tests for your & implementation. Mike
In Section
Seekers of Perl Wisdom

