在python中将16位int拆分为两个8位整数

nrn*_*nrn 5 python math

我必须将给定的16位整数转换为两个8位整数,然后将其作为输出并用作输出,其中它们将获取两个8位整数并将它们重新组合为16位输入(不幸的是我无法控制).我的解决方案有效,但感觉不洁净.对于粗数我移位原始数字,对于细数,我看它模256.

那么我应该为粗数进行分区,还是应该将最低8位用于精确数字(如果是这样的话,怎么样?)?

或者我疯了,使用两种不同的方法来分割数字不是问题?

def convert(x):
    ''' convert 16 bit int x into two 8 bit ints, coarse and fine.

    '''
    c = x >> 8  # The value of x shifted 8 bits to the right, creating coarse.
    f = x % 256  # The remainder of x / 256, creating fine.
    return c, f
Run Code Online (Sandbox Code Playgroud)

Shi*_*zou 13

我会做

c = (x >> 8) & 0xff
f = x & 0xff
Run Code Online (Sandbox Code Playgroud)

它更安全,参见例如

>>> (10303 >> 8) & 0xff
40
>>> (1030333333 >> 8) & 0xff
163
>>> (1030333333 >> 8) 
4024739
Run Code Online (Sandbox Code Playgroud)

因为在python中你不能控制数字是否是16位,你必须强制它最多16位值.如果您确定具有16位值,则不需要这样做,但这样功能更通用,并且无论容器包含什么,您都只能对16位值感兴趣.


tzo*_*zot 7

在python中,bit-fiddling没有任何特别的优势,所以我会选择:

c, f= divmod(your_number, 256)
Run Code Online (Sandbox Code Playgroud)

编辑:为了让你的意图更加明显的挑战的权力-的二源代码查看器(如果这样的猛兽存在),可以取代普通的256有更多的丰富多彩的选择,比如1<<8,2**8,0x1000400.自2.5以来由窥视孔优化器完成的常量折叠确保它们中的任何一个与使用完全相同256(我显然在谈论前两个替代方案,它们是评估的表达式256;后两个常量256).

$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import dis
>>> dis.dis(compile("c, f= divmod(your_number, 1<<8)", "", "exec"))
  1           0 LOAD_NAME                0 (divmod)
              3 LOAD_NAME                1 (your_number)
              6 LOAD_CONST               3 (256)
              9 CALL_FUNCTION            2
             12 UNPACK_SEQUENCE          2
             15 STORE_NAME               2 (c)
             18 STORE_NAME               3 (f)
             21 LOAD_CONST               2 (None)
             24 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)