예제 #1
0
def binary_to_hex(number):
    """
    Convert a 16-bit binary number to hexadecimal.
    TODO: Implement this function.

    :param number: A bitstring representing the number to convert
    :return: A hexadecimal string, the converted number
    """
    hex_str = ""
    str_pieces = [number[i:i + 4] for i in range(0, len(number), 4)]
    for i in range(len(str_pieces)):
        if str_pieces[i] == "1010":
            hex_str = "A" + hex_str
        elif str_pieces[i] == 1011:
            hex_str = "B" + hex_str
        elif str_pieces[i] == 1100:
            hex_str = "C" + hex_str
        elif str_pieces[i] == 1101:
            hex_str = "D" + hex_str
        elif str_pieces[i] == 1110:
            hex_str = "E" + hex_str
        elif str_pieces[i] == 1111:
            hex_str = "E" + hex_str
        else:
            num = binary.binary_to_decimal("0000" + str_pieces[i])
            num_str = "%d" % (num)
            hex_str = num_str + hex_str
    return "0x" + hex_str[::-1]
예제 #2
0
 def test11_binary_to_decimal(self):
     msg = "Testing basic binary-to-decimal conversion"
     self.assertEqual(bn.binary_to_decimal("01111111"), 127, msg)
예제 #3
0
 def test04_binary_to_decimal(self):
     msg = "Testing basic binary-to-decimal conversion"
     self.assertEqual(bn.binary_to_decimal("00000101"), 5, msg)
     self.assertEqual(bn.binary_to_decimal("10101000"), 168, msg)
예제 #4
0
 def test10_binary_to_decimal(self):
     msg = "Testing basic binary-to-decimal conversion"
     self.assertEqual(bn.binary_to_decimal("10000000"), -128, msg)