Data representation · GCSE · Edexcel 1CP2 2.1.2 · about 12 min
Signed 8-bit integers, and why the same adder works for them.
[1 mark]Write -5 in 8-bit two's complement.
[1 mark]What is 11111111 in 8-bit two's complement?
[1 mark]What range can an 8-bit two's complement number hold?
[1 mark]What does a leftmost bit of 1 mean in two's complement?
Write to_twos(n) yourself for -128 to 127 (you may use format(n, "08b") for the positive part). Print the 8-bit two's complement of 42, -42 and -128, one per line, in the form -42 = 11010110.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
def to_twos(n):
return format(n, "08b")The hint students can ask for: For a negative n: write -n in 8-bit binary, flip every bit, and add 1.
from bugbot import *
connect()
def to_twos(n):
if n >= 0:
return format(n, "08b")
flipped = ""
for bit in format(-n, "08b"):
flipped = flipped + ("0" if bit == "1" else "1")
return format(int(flipped, 2) + 1, "08b")
for n in [42, -42, -128]:
print(n, "=", to_twos(n))
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.