diff --git a/README.md b/README.md index 37bfb66..c177f08 100644 --- a/README.md +++ b/README.md @@ -260,6 +260,10 @@ Once imported, you can use any of the functions listed below. def number_to_engineering_notation(number): """Convert the given number to engineering notation.""" ``` + - ```python + def hex_get_bytes(hex_number, number_of_bytes): + """Reduce a hex number number to a specific number of bytes. For example, (0x123456,2) returns '0x1234'.""" + ``` ## Development diff --git a/d8s_math/maths.py b/d8s_math/maths.py index 029eda1..4fddc5d 100644 --- a/d8s_math/maths.py +++ b/d8s_math/maths.py @@ -690,3 +690,16 @@ def number_to_engineering_notation(number): decimal_form = decimal.Decimal(number) return decimal_form.normalize().to_eng_string() + +def hex_get_bytes(hex_number, number_of_bytes): + length = len(hex(hex_number)) - 2 + hex_num_bytes = length/2 + # print(type(hex_num_bytes)) + # print(type(number_of_bytes)) + # print(hex_num_bytes - number_of_bytes) + if ((hex_num_bytes < number_of_bytes) or (hex_num_bytes == number_of_bytes)): + return hex(hex_number) + else: + hex_number = hex_number >> math.floor((8*(hex_num_bytes - number_of_bytes))) + final_hex = hex(hex_number) + return final_hex