• <tfoot id='aEsDR'></tfoot>
    • <bdo id='aEsDR'></bdo><ul id='aEsDR'></ul>

      1. <legend id='aEsDR'><style id='aEsDR'><dir id='aEsDR'><q id='aEsDR'></q></dir></style></legend>

      2. <small id='aEsDR'></small><noframes id='aEsDR'>

      3. <i id='aEsDR'><tr id='aEsDR'><dt id='aEsDR'><q id='aEsDR'><span id='aEsDR'><b id='aEsDR'><form id='aEsDR'><ins id='aEsDR'></ins><ul id='aEsDR'></ul><sub id='aEsDR'></sub></form><legend id='aEsDR'></legend><bdo id='aEsDR'><pre id='aEsDR'><center id='aEsDR'></center></pre></bdo></b><th id='aEsDR'></th></span></q></dt></tr></i><div id='aEsDR'><tfoot id='aEsDR'></tfoot><dl id='aEsDR'><fieldset id='aEsDR'></fieldset></dl></div>

        Python 将字符串转换为字节

        时间:2023-07-23

              <bdo id='LGYoX'></bdo><ul id='LGYoX'></ul>

              <legend id='LGYoX'><style id='LGYoX'><dir id='LGYoX'><q id='LGYoX'></q></dir></style></legend>
            • <i id='LGYoX'><tr id='LGYoX'><dt id='LGYoX'><q id='LGYoX'><span id='LGYoX'><b id='LGYoX'><form id='LGYoX'><ins id='LGYoX'></ins><ul id='LGYoX'></ul><sub id='LGYoX'></sub></form><legend id='LGYoX'></legend><bdo id='LGYoX'><pre id='LGYoX'><center id='LGYoX'></center></pre></bdo></b><th id='LGYoX'></th></span></q></dt></tr></i><div id='LGYoX'><tfoot id='LGYoX'></tfoot><dl id='LGYoX'><fieldset id='LGYoX'></fieldset></dl></div>

              <small id='LGYoX'></small><noframes id='LGYoX'>

                    <tbody id='LGYoX'></tbody>
                1. <tfoot id='LGYoX'></tfoot>

                  本文介绍了Python 将字符串转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我正在尝试进行一些串行输入和输出操作,其中之一是将 8x8 阵列发送到外部设备 (Arduino).pySerial 库要求我发送的信息是一个字节.但是,在我的 python 代码中,8x8 矩阵由 <class 'str'> 类型组成.这是我的发送功能:

                  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 <class 'str'>. 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()
                  

                  现在,我有一个类 Matrix,其中包含一个字段 map,这是有问题的数组,我也会在此处包含该代码,但问题是我遇到的是数组中的每个元素都是 str 类型,但我需要将其转换为字节.我可以忽略可能的数据丢失,因为在实践中,我只使用 0 和 1.

                  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.

                  我的矩阵类:

                  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('
                  ')
                          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('
                  ')
                          return matrix
                  

                  推荐答案

                  要在 Python 中将 unicode 字符串转换为字节字符串,请执行以下操作:

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

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

                  将字节字符串转换为 unicode 字符串:

                  To transform a byte string to a unicode string:

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

                  参见 编码 和 decode 在标准库中.

                  See encode and decode in the Standard library.

                  可用的编码记录在此表中.常用的有utf_8utf_8_sigasciilatin_1cp1252.请参阅 UTF-8、BOM, ASCII, Latin-1 和 Windows-1252 在维基百科.

                  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.

                  raw_unicode_escape 有助于调试.请参阅此表.

                  Helpful for debbugging can be raw_unicode_escape. See this table.

                  这篇关于Python 将字符串转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  上一篇:一段时间后,使用 PySerial 从 Arduino 到 Raspberry Pi 的串行接收停止 下一篇:尝试在 WinXP 上使用 pyserial 打开串行端口 -&gt;“拒绝访问"

                  相关文章

                  1. <i id='6SDUd'><tr id='6SDUd'><dt id='6SDUd'><q id='6SDUd'><span id='6SDUd'><b id='6SDUd'><form id='6SDUd'><ins id='6SDUd'></ins><ul id='6SDUd'></ul><sub id='6SDUd'></sub></form><legend id='6SDUd'></legend><bdo id='6SDUd'><pre id='6SDUd'><center id='6SDUd'></center></pre></bdo></b><th id='6SDUd'></th></span></q></dt></tr></i><div id='6SDUd'><tfoot id='6SDUd'></tfoot><dl id='6SDUd'><fieldset id='6SDUd'></fieldset></dl></div>
                    • <bdo id='6SDUd'></bdo><ul id='6SDUd'></ul>

                    1. <tfoot id='6SDUd'></tfoot>

                      <small id='6SDUd'></small><noframes id='6SDUd'>

                      <legend id='6SDUd'><style id='6SDUd'><dir id='6SDUd'><q id='6SDUd'></q></dir></style></legend>