Skip to content

Instantly share code, notes, and snippets.

@yarko
Last active January 28, 2018 01:23
Show Gist options
  • Save yarko/f819971d3b588f3966e6e1fc9f79e6ff to your computer and use it in GitHub Desktop.
Save yarko/f819971d3b588f3966e6e1fc9f79e6ff to your computer and use it in GitHub Desktop.
correct bit complement operation in python (it doesn't seem to work as expected - i.e. on unsigned value - or byte value)
# coding: utf-8
'''
Tried to bit-invert a CSS hex-encoded color using python, but
couldn't get expected output with bit-invert operator.
I.e. this didn't do what I expected:
print(f'#{old_color:x} => #{~old_color:x}')
Besides acting on an apparently arbitrary length integer (rather
than an unsigned (i.e. sign-not-interpreted) bit pattern, the operator
also only (!) works on integers - but not bytes.
This did it, is one solution.
example usage:
old_color = 0x83fdcc
print(f'#{old_color:x} => #{bit_invert(old_color):x}')
'''
def byte_mask(v):
'''
returns a byte mask for the byte_length of v,
e.g. for a 2 byte value, returns 0xffff
'''
n = v.bit_length()
# ensure #bits is an integral of 8
shift_bits = n if n%8 ==0 else (n//8+1)*8
return (1<<shift_bits)-1
bit_invert = lambda v: ~v&byte_mask(v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment