在python中将16位int拆分为两个8位int [英] Splitting a 16 bit int into two 8 bit ints in python

查看:118
本文介绍了在python中将16位int拆分为两个8位int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将给定的16位整数转换为两个8位整数,然后将其用作输出,在其中将两个8位整数作为标题,并将它们重新组合为16位输入(不幸的是,这超出了我的控制范围)).我的解决方案有效,但感觉不干净.对于粗略的数字,我将原始数字位移一点,对于细微的数字,我将其以256为模.

I have to convert a given 16 bit integer into two 8 bit integers, which are then taken and used as output, where they are headed takes the two 8 bit integers and recombines them as 16 bit input (unfortunately out of my control). My solution works, but feels unclean. For the coarse number I am bit shifting the original number, and for the fine number I am looking at it modulo 256.

那么我应该对粗数进行地板分割,还是对细数进行最低8位处理(如果可以,怎么办?)?

So should I be doing floor division for the coarse number, or should I be taking the lowest 8 bits for the fine number (and if so how?)?

还是我疯了,使用两种不同的方法来拆分数字不是问题吗?

Or am I crazy and using two different methods to split the number is not a problem?

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

推荐答案

我会做

c = (x >> 8) & 0xff
f = x & 0xff

它更安全,例如参见

>>> (10303 >> 8) & 0xff
40
>>> (1030333333 >> 8) & 0xff
163
>>> (1030333333 >> 8) 
4024739

由于在python中,如果数字不是16位,则无法控制,因此必须将其强制为最大16位的值.如果您确定具有16位值,则不需要此操作,但是通过这种方式,该函数更通用,无论容器包含什么内容,都只对16位值感兴趣.

Since in python you can't control if the number is or not a 16bit, you have to force it into an at most 16-bit value. This is not needed if you're sure to have a 16-bit value, but this way the function is more general and allows you to be interested only in 16-bit values, no matter what the container contains.

这篇关于在python中将16位int拆分为两个8位int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆