On 9/12/11 Mon  Sep 12, 2011  12:47 PM, "Ryan Munson"
<ryan.barrac...@elboardo.com> scribbled:

> The full exercise states:
> 
> Write a program that asks for a decimal number less than 256 and converts
> it to binary. (Hint: You may want to use the bitwise and operator 8 times.)
> 
> Since 256 is 2^8, I am assuming using a computation of 2**8 is involved.

I don't see where 2**8 is involved anywhere.

Decimal and binary are two different ways of representing integer numbers.
The number represented by decimal '17' is also represented by binary
'010001' ( and octal '21').

The 'bitwise-and' operator allows you to query the status of individual bits
in the binary representation of a number. If your decimal number has been
assigned to the Perl variable $dec, then the expression ($dec & 1) will be
true if the lowest bit of the binary form of $dec is 1. Likewise, ($dec & 2)
will be true if the second-lowest bit of $dec is 1, and so on up to ($dec &
128). Since your number is supposed to be "less than 256", i.e. 255 or less,
you will only need 8 bits to represent all possible binary numbers (from 0
to 255).

Normally, rather than doing 8 separate similar things, a programmer will
write a loop that is iterated 8 times. However, if your book says or implies
that you do this exercise without if statements or loops, you may have to
have 8 different explicit expressions using the bitwise-and, each statement
testing a different bit of $dec.

With this information and what Brandon has given you, can you attempt to
rewrite your program?

Cheat1: Perl printf has the %b descriptor that will print any integer in
binary form.

Cheat2: You are not the first person to have trouble with this exercise:

<http://www.perlmonks.org/?node_id=780435>

Good luck!



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to