forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add decimal_to_binary_ip.py (keon#339)
* Add decimal_to_binary_ip.py Converts dotted_decimal ip address to binary ip address. * Include tests for decimal_to_binary_ip Some tests cases for decimal_to_binary_ip function. * Fix TestDecimalToBinaryIP method name changed method from test_int2base to test_decimal_to_binary_ip * Import decimal_to_binary_ip Added decimal_to_binary_ip to imports * Update README.md Add to decimal_to_binary_ip * resolve conflicts in test_maths
- Loading branch information
Showing
4 changed files
with
46 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters