【问题标题】:Create a bytearray from hex constants从十六进制常量创建一个字节数组
【发布时间】:2018-04-13 01:37:21
【问题描述】:

我定义了一堆单独的十六进制字符,我需要将它们写入设备串行端口。我将如何从它们中创建一个字节数组? 例如:

import serial
# There is a series of predefined hex characters for talking to this device. Some
# These are just some random examples I made up 

START_BYTE = 0x03
END_BYTE = 0x10
RANDOM_BYTE1 = 0xCE
RANDOM_BYTE2 = 0xAB

# Assume I opened port and is connected
sp = serial.open()

# Now in some random method I want to write to the port the sequence of
# [START_BYTE, RANDOM_BYTE1, END_BYTE]
# How would I write this? I tried
sp.write([START_BYTE, RANDOM_BYTE1, END_BYTE])
sp.write(bytearray([START_BYTE, RANDOM_BYTE1, END_BYTE]))
# But I do not get the response on the machine I want.

最终 RANDOM_BYTE 将是一些数据位,根据情况可能是 1 到 10 个字节。所以会是

[START_BYTE, DATA_BYTES, END_BYTE]

我做错了什么?

我正在使用 python 2.7

【问题讨论】:

    标签: python arrays python-2.7


    【解决方案1】:

    您需要的是bytes(或str ...

    >>> bytes(bytearray([0x03, 0xce, 0xab]))
    '\x03\xce\xab'
    

    【讨论】:

    • 我知道它必须是简单的东西。谢谢!
    猜你喜欢
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2018-04-21
    相关资源
    最近更新 更多