-
Notifications
You must be signed in to change notification settings - Fork 4
/
13_ascii_to_integer.py
executable file
·60 lines (43 loc) · 1.44 KB
/
13_ascii_to_integer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/python
# The atoi function in C converts a string character to an integer.
#+Write a shell script function that performs the same operation.
#+Likewise, write a shell script function that does the inverse,
#+mirroring the C itoa function which converts an integer into an ASCII character.
import re
# Use a little modified version of exercise 12 function
def is_int(value):
''' Check if "value" variable contains
only int digits or it is just string '''
int_regexp = '^[0-9]+$'
if not isinstance(value, basestring):
return False
if re.match(int_regexp, value):
return True
else:
return False
def atoi(string):
num_pattern = re.compile('^[0-9]+')
if re.match(num_pattern, string):
return int(re.findall(num_pattern, string)[0])
else:
return 0
def itoa(int_num, base=10):
if is_int(int_num):
return "This is not integer"
if base not in (2, 8, 10, 16):
return "Wrong base format"
if base == 2:
return bin(int_num)[2:]
if base == 8:
return oct(int_num)[1:]
if base == 10:
return int(int_num)
if base == 16:
return hex(int_num)[2:]
if __name__ == '__main__':
number = atoi("0123.2d1sd23d")
print number # return 123
print itoa(number, 2) # return 1111011
print itoa(number, 8) # return 173
print itoa(number, 10) # return 123
print itoa(number, 16) # return 7b