1

I am trying to read a string of bits and print them to a separate file in a meaningful way.

Essentially, I am reading data from a sensor (a serial output), which is in hex. I then want to convert this information to binary, and then have it displayed graphically to a webpage. Whenever the sensor takes a reading, it'll print: 17E12000 to a terminal screen. I then convert this number to: 00010111111000010010000000000000, which gets broken up into nine different categories as: 00 010 111 111 000 01 0010 0000 00000000. I can't seem to figure out how to split the binary string into arbitrary lengths (i.e. length of two, then length of three, length of three ... length of two, length of four, length of eight. Once I get the values separated as such, I need to convert them to decimal to display them similar to the following:

DoT: 0
DoD: 2
MAG INT: 7
VEH INT: 7
PERS INT: 0
Duration: 1
CLASS: 2
EXT Sens type: 0
Ext: S

This latter part I think I can handle. I really could use some insight on how to brake up a string such as 00010111111000010010000000000000 to be printed as 00 010 111 111 000 01 0010 0000 00000000. Each grouping can be save to a newline or just be separated via spaces as shown.

My code will read an input such as: TXM 02 030 01 00 17E12000 from a file (which was printed to the file from a terminal output). I'm only concerned about the last grouping, which is 17E12000.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
newB.79
  • 11
  • 2
  • Hmm, I know how to do this manually by xor-ing bitmasks, but I think the better way to do it is with a [struct](https://docs.python.org/3/library/struct.html). BTW welcome to Stack Overflow! Check out the [tour]. – wjandrea Nov 12 '19 at 17:14
  • It would help to give a specific example of input and desired output. See [mre] and [ask] for other advice. – wjandrea Nov 12 '19 at 17:16
  • Does this answer your question? [Convert bytes to bits in python](https://stackoverflow.com/questions/8815592/convert-bytes-to-bits-in-python), especially [Anony-Mouse's answer](https://stackoverflow.com/a/8816011/4518341) – wjandrea Nov 12 '19 at 17:18
  • Thanks for the help! I created the variable n = [2, 3, 3, 3, 3, 2, 4, 4, 8, 0] Afterwards, I used this line of code to break the string up. f4.write((('\n'.join([s[sum(n[:i]):sum(n[:i+1])] for i in range(len(n))])))) – newB.79 Nov 13 '19 at 02:41

0 Answers0