def to_twos_complement(val):
    """
    >>> to_twos_complement(-7)
    249
    >>> bin(to_twos_complement(-7))
    '0b11111001'
    >>> bin(to_twos_complement(-1))
    '0b11111111'
    >>> bin(to_twos_complement(1))
    '0b1'
    >>> bin(to_twos_complement(256))
    Traceback (most recent call last):
    ...
    AssertionError: val expected to be in range -128..127. Was: 256
    """
    assert -128 <= val <= 127, 'val expected to be in range -128..127. Was: %s' % val
    if val < 0:
        val = -((val ^ 255) + 1)
    return val
