python字符串转换字节_Python将字符串转换为字节

I am trying to do some serial input and output operations, and one of those is to send an 8x8 array to an external device (Arduino). The pySerial library requires that the information that I send be a byte. However, in my python code, the 8x8 matrix is made up of types . Here's my sending function:

import serial

import Matrix

width = 8

height = 8

portName = 'COM3'

def sendMatrix(matrix):

try:

port = serial.Serial(portName, 9600, timeout = 1000000)

port.setDTR(0)

print("Opened port: \"%s\"." % (portName))

receivedByte = port.read()

print(int(receivedByte))

if (receivedByte == '1'):

port.write('1')

bytesWritten = 0

for row in range(8):

for col in range(8):

value = matrix.getPoint(col, row)

bytesWritten += port.write(value)//ERROR HERE!

print(int(port.read()));

port.close()

print("Data (%d) sent to port: \"%s\"." % (bytesWritten, portName))

except:

print("Unable to open the port \"%s\"." % (portName))

def main():

matrix = Matrix.Matrix.readFromFile('framefile', 8, 8)

matrix.print()

print(type(matrix.getPoint(0, 0)))

print(matrix.getPoint(1, 1))

sendMatrix(matrix)

main()

Now, I have a class Matrix, which contains a field map, which is the array in question, and I will include that code here too, but the problem I'm having is that each element in the array is of type str, but I need to convert it to a byte. I can disregard possible loss of data, since in practice, I only use 0's and 1's.

My Matrix Class:

class Matrix(object):

def __init__(self, width, height):

self.width = width

self.height = height

self.map = [[0 for x in range(width)] for y in range(height)]

def setPoint(self, x, y, value):

if ((x >= 0) and (x < self.width) and (y >= 0) and (y < self.height)):

self.map[y][x] = value

def getPoint(self, x, y):

if ((x >= 0) and (x < self.width) and (y >= 0) and (y < self.height)):

return self.map[y][x]

def print(self):

for row in range(self.height):

for col in range(self.width):

print(str(self.map[row][col])+" ", end="")

print()

def save(self, filename):

f = open(filename, 'w')

for row in range(self.height):

for col in range(self.width):

f.write(str(self.map[row][col]))

f.write('\n')

f.close()

def toByteArray(self):

matrixBytes = bytearray(self.width * self.height)

for row in range(self.height):

for col in range(self.width):

matrixBytes.append(int(self.map[row][col]))

return matrixBytes

def getMap(self):

return self.map

def readFromFile(filename, width, height):

f = open(filename, 'r')

lines = list(f)

matrix = Matrix(width, height)

f.close()

for row in range(len(lines)):

matrix.map[row] = lines[row].strip('\n')

return matrix

解决方案

To transform a unicode string to a byte string in Python do this:

>>> 'foo'.encode('utf_8')

b'foo'

To transform a byte string to a unicode string:

>>> b'foo'.decode('utf_8')

'foo'

See encode and decode in the Standard library.

The available encodings are documented in this table. Commonly used ones are utf_8, utf_8_sig, ascii, latin_1 and cp1252. See UTF-8, BOM, ASCII, Latin-1 and Windows-1252 at Wikipedia.

Helpful for debbugging can be raw_unicode_escape. See this table.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值