Complete the code to represent the negative number -5 in 8-bit two's complement.
binary = "[1]" # 8-bit two's complement of -5
The 8-bit two's complement of -5 is 11111011. This is found by inverting the bits of 5 (00000101) and adding 1.
Complete the code to calculate the decimal value of the 8-bit two's complement binary '11110110'.
decimal_value = [1] # decimal value of 11110110
The binary 11110110 in 8-bit two's complement represents -10. The leading 1 means it's negative. Invert bits and add 1 to find magnitude.
Fix the error in the code that converts a negative decimal number to its 8-bit two's complement binary string.
def to_twos_complement(n): if n >= 0: return format(n, '08b') else: return format([1], '08b') # fix this line
For negative numbers, adding 256 (2^8) to n gives the correct 8-bit two's complement representation.
Fill both blanks to create a dictionary comprehension that maps numbers to their 8-bit two's complement binary strings only if the number is negative.
twos_complement_map = {num: format([1], '08b') for num in numbers if num [2] 0}The comprehension adds 256 to negative numbers to get their two's complement binary. The condition filters numbers less than zero.
Fill all three blanks to create a dictionary comprehension that maps numbers to their 8-bit two's complement binary strings, handling both positive and negative numbers.
twos_complement = {n: format([1], '08b') for n in nums}
# where [2] = n if n >= 0 else [3]The comprehension uses a conditional expression: if n is non-negative, use n; otherwise, add 256 to get two's complement.
