Skip to content
Open
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
49 changes: 49 additions & 0 deletions conversions/ascii_to_char.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""
Convert an ASCII integer (0-255) to its corresponding character.

Example:
>>> ascii_to_char(65)
'A'
>>> ascii_to_char(97)
'a'
>>> ascii_to_char(36)
'$'
>>> ascii_to_char(300)
Traceback (most recent call last):
...
ValueError: ASCII value must be in the range 0-255.

Reference:
https://en.wikipedia.org/wiki/ASCII
"""


def ascii_to_char(ascii_value: int) -> str:
"""
Convert an ASCII integer (0-255) into its corresponding character.

Args:
ascii_value (int): Integer representing an ASCII code (0-255).

Returns:
str: The corresponding character.

Raises:
ValueError: If the input is not within 0-255 inclusive.

>>> ascii_to_char(65)
'A'
>>> ascii_to_char(97)
'a'
>>> ascii_to_char(36)
'$'
>>> ascii_to_char(300)
Traceback (most recent call last):
...
ValueError: ASCII value must be in the range 0-255.
"""
if not isinstance(ascii_value, int):
raise TypeError("Input must be an integer.")
if not 0 <= ascii_value <= 255:
raise ValueError("ASCII value must be in the range 0-255.")
return chr(ascii_value)
49 changes: 49 additions & 0 deletions conversions/char_to_ascii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""
Convert a single character to its ASCII integer value.

Example:
>>> char_to_ascii('A')
65
>>> char_to_ascii('a')
97
>>> char_to_ascii('$')
36
>>> char_to_ascii('AB')
Traceback (most recent call last):
...
ValueError: Input must be a single character

References:
https://en.wikipedia.org/wiki/ASCII
"""


def char_to_ascii(char: str) -> int:
"""
Convert a single character to its ASCII integer value.

Args:
char (str): A single character string.

Returns:
int: ASCII integer value corresponding to the character.

Raises:
ValueError: If input is not a single character.

>>> char_to_ascii('A')
65
>>> char_to_ascii('a')
97
>>> char_to_ascii('$')
36
>>> char_to_ascii('')
Traceback (most recent call last):
...
ValueError: Input must be a single character
"""
if not isinstance(char, str):
raise TypeError("Input must be a string.")
if len(char) != 1:
raise ValueError("Input must be a single character")
return ord(char)