[Tutor] Hex to Str - still an open issue
sandip at lug-delhi.org
Sun Feb 6 02:14:50 CET 2005
Liam Clarke wrote:
> Sandip -
> Just looking at this -
> i = 456
> s = ''
> while i:
> s = str(i % 2) + s
> This works, far simpler than mine, which is always infuriating, but my
> question is, how exactly?
> if I have the number 15, when it divides by 2, it will become 7. Yet
> no error is introduced into the binary. Argggg. Driving me nuts trying
> to figure out how. I thought maybe a larger odd number would do it,
> but no.
> i = 320977545
> s = 10011001000011011101010001001
> Chuck that into ol' calc, and I get, 320977545.
> Can anyone shed some more light on this?
If you imagine the number being displayed in binary inside your calculator,
i % 2, gives us the rightmost bit of the number (has to be 0 or 1)
1/=2 just right shifts the number by one.
So if you consider 15,
a. i % 2 will give you "1".
b. So even if 15/2 gives you 7, it is ok, as the odd bit has been taken
care of in (a).
More information about the Tutor