6

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

2
  • So, basically you are asking how, given a 16 bit number, you can get the number corresponding to the first and the last 8 bits? Commented Mar 20, 2015 at 23:00
  • yep :) that would be the simple way of saying it. Commented Mar 20, 2015 at 23:02

3 Answers 3

12

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)
Sign up to request clarification or add additional context in comments.

1 Comment

you could write 255 as 0b11111111 or 0xff
3

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))

Comments

0

Here's an example, not sure if it applies since you haven't provided example code.

from binascii import hexlify
from sys import version_info

if version_info >= (3, 0):
    return bin(int.from_bytes(text_data.encode(), 'big'))
else:
    return bin(int(hexlify(text_data), 16))

This was taken from code I already use in a one time pad encryption module i wrote. It converts strings just fine, heres the the entire method.

def _string_converter(self, text_data):
    """Takes a given string or file and converts it to binary."""
    if version_info >= (3, 0):
        return bin(int.from_bytes(text_data.encode(), 'big'))
    else:
        return bin(int(hexlify(text_data), 16))

As an example to how to convert a string into 16bit binary, it could be split into 8 bit segments, probably easiest with some list magic.

1 Comment

You forgot to split the returned string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.