I have a list of numbers in the range 0-1023. I would like to convert them to integers such that 1023 maps to -1, 1022 maps to -2 etc.. while 0, 1, 2, ....511 remain unchanged.
I came up with a simple:
def convert(x):
return (x - 2**9) % 2**10 - 2**9
is there a better way?
asked Jan 28, 2014 at 23:44
Fra
5,2189 gold badges36 silver badges51 bronze badges
3 Answers 3
Naivest possible solution:
def convert(x):
if x >= 512:
x -= 1024
return x
answered Jan 28, 2014 at 23:52
Brave Sir Robin
1,0466 silver badges9 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
John1024
Alternatively, reducing three lines to one:
return x if x < 512 else x - 1024Brave Sir Robin
or
return x - 1024 * (x >= 512)ashastral
@rmartinjak, multiplying by a boolean requires Python to do an extra cast, and as a result that solution is a bit slower than the other ones. Your original solution and John1024's seem to be roughly equivalent. I haven't done any rigorous testing yet, though.
max_uint_value = 512
def unassigned_to_int(uint):
return uint - max_uint_value if uint >= max_uint_value else uint
answered Jun 8, 2018 at 17:37
Ilan Olkies
4535 silver badges10 bronze badges
Comments
lang-py
%operator yields a negative (or zero) value for a negative left operand, so the code could perhaps be made clearer by changing(x - 2**9)to(x + 2**9). Aside from that, this seems like a reasonable implementation.