def test05_decimal_to_binary(self): msg = "Testing basic decimal-to-binary conversion" self.assertEqual(bn.decimal_to_binary(5), "00000101", msg) self.assertEqual(bn.decimal_to_binary(-10), "11110110", msg) self.assertEqual(bn.decimal_to_binary(-37), "11011011", msg) with self.assertRaises(OverflowError): bn.decimal_to_binary(150) with self.assertRaises(OverflowError): bn.decimal_to_binary(-132)
def hex_to_binary(number): """ Convert a hexadecimal number to 16-bit binary. TODO: Implement this function. :param number: A hexadecimal string, the number to convert :return: A bitstring representing the converted number """ bin_str = "" num = "0" d = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 } concat_str = number[2:] for str_piece in concat_str: if str_piece == "A": bin_str = bin_str + "1010" elif str_piece == "B": bin_str = bin_str + "1011" elif str_piece == "C": bin_str = bin_str + "1100" elif str_piece == "D": bin_str = bin_str + "1101" elif str_piece == "E": bin_str = bin_str + "1110" elif str_piece == "F": bin_str = bin_str + "1111" else: num = d[str_piece] bin_str = bin_str + binary.decimal_to_binary(num)[4:] return bin_str
def test05_decimal_to_binary(self): msg = "Testing basic decimal-to-binary conversion" self.assertEqual(bn.decimal_to_binary(5), "00000101", msg)
def test16_decimal_to_binary(self): msg = "Testing basic decimal-to-binary conversion" with self.assertRaises(OverflowError): bn.decimal_to_binary(128)
def test15_decimal_to_binary(self): msg = "Testing basic decimal-to-binary conversion" self.assertEqual(bn.decimal_to_binary(-128), "10000000", msg)
def test14_decimal_to_binary(self): msg = "Testing basic decimal-to-binary conversion" self.assertEqual(bn.decimal_to_binary(127), "01111111", msg)