Functional schmunctional...
Terry Reedy
tjreedy at udel.edu
Tue Feb 10 17:57:54 EST 2009
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
More information about the Python-list
mailing list