Add decimal_to_binary_ip.py by victore07 · Pull Request #339 · keon/algorithms · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
1 change: 1 addition & 0 deletions algorithms/maths/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from .base_conversion import *
from .decimal_to_binary_ip import *
from .extended_gcd import *
from .factorial import *
from .gcd import *
Expand Down
27 changes: 27 additions & 0 deletions algorithms/maths/decimal_to_binary_ip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""
Given an ip address in dotted-decimal representation, determine the
binary representation. For example,
decimal_to_binary(255.0.0.5) returns 11111111.00000000.00000000.00000101
accepts string
returns string
"""

def decimal_to_binary_util(val):
bits = [128, 64, 32, 16, 8, 4, 2, 1]
val = int(val)
binary_rep = ''
for bit in bits:
if val >= bit:
binary_rep += str(1)
val -= bit
else:
binary_rep += str(0)

return binary_rep

def decimal_to_binary_ip(ip):
values = ip.split('.')
binary_list = []
for val in values:
binary_list.append(decimal_to_binary_util(val))
return '.'.join(binary_list)
19 changes: 17 additions & 2 deletions tests/test_maths.py