Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a 16 bit int into two 8 bit ints in python

Tags:

python

math

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.

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
like image 214
nrn Avatar asked Jun 26 '10 09:06

nrn


1 Answers

I would do

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

It is safer, see e.g.

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

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.

like image 155
ShinTakezou Avatar answered Sep 17 '22 07:09

ShinTakezou