4

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?

1
  • 1
    In some programming languages, the % 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. Commented Jan 28, 2014 at 23:52

3 Answers 3

5

Naivest possible solution:

def convert(x):
    if x >= 512:
        x -= 1024
    return x
Sign up to request clarification or add additional context in comments.

3 Comments

Alternatively, reducing three lines to one: return x if x < 512 else x - 1024
or return x - 1024 * (x >= 512)
@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.
2
def convert(x):
    return x - (x >> 9) * 1024

Using ctypes:

from ctypes import c_short

def convert(x):
    return c_short(x << 6).value >> 6

1 Comment

perfect answer, I may add some explanations
0
 max_uint_value = 512

 def unassigned_to_int(uint):
      return uint - max_uint_value if uint >= max_uint_value else uint

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.