문제

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?

도움이 되었습니까?

해결책

Naivest possible solution:

def convert(x):
    if x >= 512:
        x -= 1024
    return x

다른 팁

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
 max_uint_value = 512

 def unassigned_to_int(uint):
      return uint - max_uint_value if uint >= max_uint_value else uint
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top