Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with binary in Python, Splitting numbers

Tags:

python

binary

I have a module that takes 2 X 8bit numbers in Decimal format, with a specific structure

each number must start with the same 4 bits = 0011 followed be a varible 8 bits followed by 4 bits that are ignored so set to 0000

So to caculate the 16bit number is simple enough

the varible number * 16 will shift it the 4 bits to the left, and adding 12288 = 0011|000000000000 will give me the desired result.

so if my input number is 19 for example

19 X 16 + 12288 = 12592 = 0011000100110000

the next step is to split it in to two X 8 bit numbers

00110001 | 00110000 = 49, 48

how in python can i go from 12592 to 49,48 efficiently.

Never worked in binary in a script so all a bit new.

Cheers

like image 420
DevilWAH Avatar asked Mar 20 '15 22:03

DevilWAH


People also ask

How do you divide binary numbers in Python?

We start by converting 100 to it's binary digits: 100 = 64 + 32 + 4 = [1,1,0,0,1,0,0] . We loop through the entries, multiplying by 2 and adding the current digit. At each step, if the divisor < the current dividend, we multiply the result by 2 and add 1.

How does Python deal with binary numbers?

In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.

How do you multiply binary in Python?

We can multiply two binary numbers in two ways using python, and these are: Using bin() functions and. Without using pre-defined functions.


2 Answers

To get the first 8 bits, just shift it to the right by 8 bits.

   0011000100110000 >> 8
==         00110001

To get the last 8 bits, mask it with 0b11111111, i.e. 255.

   0011000100110000
&  0000000011111111
-------------------
   0000000000110000

Code example:

>>> n = int("0011000100110000", 2)
>>> n
12592
>>> n >> 8, n & 255
(49, 48)

Alternatively, you could also just use divmod, but >> and & seem to be a bit faster.

>>> divmod(n, 256)
(49, 48)
like image 110
tobias_k Avatar answered Nov 14 '22 22:11

tobias_k


Make use of the bin built in function

def split16Bit(num):
    binary = bin(num)[2:].rjust(16, '0')
    return (int(binary[:8], 2), int(binary[8:], 2))
like image 29
smac89 Avatar answered Nov 14 '22 23:11

smac89