简体   繁体   中英

Convert a binary number to human readable text

I am using Python 3.3.

I get my data from a serial port and each byte I get correspond to one whole number. (no number is greater than 255, so no multi-byte numbers).

I have been trying way to long getting this written to a text file in human readable text so I am asking for help.

If I get value 0b10000111 from my serial port, how do I get this number to show up as "135" in my text file? This sounds like a simple task, but I have struggled a lot!

I also want to add a comma to separate the value (bytes).

This is what I have been trying:

import sys
import serial

port = serial.Serial('COM4', 115200)
fileID = open('output.txt', 'a')

while(1):
    data = port.read(size=1)
    if data != 0:
        #MISSING SOME CONVERSION HERE... Tried a lot of things, 
        #but none have been correct.
        fileID.write(data)
        fileID.write(',')

You know that the size of data is one, and all you're interested in is the first byte. First you need to convert that byte to an integer, then to a string.

fileID.write(str(ord(data[0])))

It is now working and I wanted to share the code with the rest of you awesome people:

import sys
import serial

port = serial.Serial('COM4', 115200, timeout=0)
data = b''

while(1):
    data = port.read()
    print(data)
    if data != b'':
        fileID = open('output.txt', 'a')
        fileID.write(str(ord(data)))
        fileID.write(',')
        fileID.close()

port.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM