Functional schmunctional...
Steve Holden
steve at holdenweb.com
Wed Feb 11 09:42:45 EST 2009
Terry Reedy wrote:
> r0g wrote:
>
>>
>> def inet2ip(n):
>> p = (n/16777216)
>> q = ((n-(p*16777216))/65536)
>> r = ((n-((p*16777216)+(q*65536)))/256)
>> s = ((n-((p*16777216)+(q*65536)+(r*256))))
>> return str(p)+"."+str(q)+"."+str(r)+"."+str(s)
>
> Beyond what other wrote:
> To future-proof code, use // instead of / for integer division.
> To get both quotient and remainder, use divmod(num,den)
> For future reading (and generalization) documenting magic constants helps.
>
> In 3.0:
>
> def inet2ip(n):
> p = (n//16777216)
> q = ((n-(p*16777216))//65536)
> r = ((n-((p*16777216)+(q*65536)))//256)
> s = ((n-((p*16777216)+(q*65536)+(r*256))))
> return str(p)+"."+str(q)+"."+str(r)+"."+str(s)
>
> def inet2ip2(n):
> p,n=divmod(n,16777216) # 1<<24
> q,n=divmod(n,65536) # 1<<16
> r,s=divmod(n,256) # 1<<8
> return str(p)+"."+str(q)+"."+str(r)+"."+str(s)
>
> print(inet2ip(1000000000), inet2ip2(1000000000))
>
>>>>
> 59.154.202.0 59.154.202.0
>
Jeez, doesn't anyone read the fine manual any more? I hope this was just
an academic exercise.
>>> socket.inet_ntoa(struct.pack("!l", 1000000000))
'59.154.202.0'
>>>
Holden's rule: when it looks simple enough to be worth including in the
standard library it may well already *be* in the standard library.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list