########################################################################### # # Copyright (c) 2019-2021 Diality Inc. - All Rights Reserved. # # THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, IN PART OR IN # WHOLE, WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER. # # @file conversions.py # # @author (last) Sean Nash # @date (last) 12-Nov-2021 # @author (original) Peter Lucia # @date (original) 02-Apr-2020 # ############################################################################ import struct from typing import List, Union def byte_to_bytearray(val: int) -> bytes: """ Converts a byte value into a byte array (little endian) @param val: (int) integer to convert to byte array @return: byte array """ if type(val) != int: raise ValueError("Expected integer but received {0} with type {1}".format(val, type(val))) return struct.pack(" bytes: """ Converts a short integer (2 bytes) value into a byte array (little endian) @param val: (int) integer to convert to byte array @return: byte array """ if type(val) != int: raise ValueError("Expected integer but received {0} with type {1}".format(val, type(val))) return struct.pack(" bytes: """ Converts an unsigned short integer (2 bytes) value into a byte array (little endian) @param val: (int) integer to convert to byte array @return: byte array """ if type(val) != int or val < 0: raise ValueError("Expected unsigned integer but received {0} with type {1}".format(val, type(val))) return struct.pack(" bytes: """ Converts an integer value into a byte array (little endian) @param val: integer to convert to byte array, bool is accepted @return: byte array """ if type(val) != bool and type(val) != int: raise ValueError("Expected integer but received {0} with type {1}".format(val, type(val))) return struct.pack(" bytes: """ Converts an integer value into a byte array (little endian) @param val: (int) integer to convert to byte array @return: byte array """ if type(val) != int or val < 0: raise ValueError("Expected unsigned integer but received {0} with type {1}".format(val, type(val))) return struct.pack(" bytes: """ Converts a float value into a byte array (little endian) @param val: float to convert to byte array, int is accepted @return:: byte array """ if type(val) != float and type(val) != int: raise ValueError("Expected float but received {0} with type {1}".format(val, type(val))) return struct.pack(' List[int]: """ Converts an integer to a bit array. For direct conversion to binary please use bin(val), as this function has a separate purpose @param val: (int) the number to convert @param num_bits: (int) the number of bits needed @return: (List[int]) The number represented in binary form as a list of 1's and 0's """ if type(val) != int: raise ValueError("Expected integer but received {0} with type {1}".format(val, type(val))) return [(val >> bit) & 1 for bit in range(num_bits - 1, -1, -1)]