Python,制定准备通过串行发送的二进制数据的正确方法
Python, Correct way to formulate Binary Data ready to be sent over serial
我需要创建一个通过串口与不同设备通信的设备。非常基本的东西。
但是,我需要做的就是传递特定的二进制数据,其余的由设备处理。
数据必须是二进制格式,我在互联网上看到过各种方法,但真的不确定什么是表示二进制数据而不是字符串的正确方法。
以下是我发现的一些示例:
b'01001011' # Is this a packed string though?
bytes(4) # This creates bytes. How do I manipulate the bits?, is this data able to send over serial?
int('01001011', 2) # Will this be treated as an integer over serial?
binascii.hexify() # This produces ASCII representation
我需要制定几个字节的信息,这将涉及我在每个字节中设置某些位,我很困惑如何去做
python 中的二进制文字如下所示:
>>> 0b11
3
>>> 0b10
2
>>> 0b100
4
您可以使用按位运算符操作位:
>>> 0b1000
8
>>> 0b1000 | 0b1
9
|
只是 or
运算符。在此处查看其他运算符:BitwiseOperators
要查看数字的二进制表示,您可以使用 string.format:
>>> "{0:b}".format(9)
'1001'
>>> "{0:b}".format(65)
'1000001'
>>> "{0:b}".format(234)
'11101010'
编辑
设置特定位的示例:
# setting off second bit
>>> bin(0b1100 & 0b1011)
'0b1000'
# setting on third bit
>>> bin(0b1100 | 0b0010)
0b1110'
请注意二进制字面值给你一个 int:
>>> type(0b1)
<type 'int'>
我需要创建一个通过串口与不同设备通信的设备。非常基本的东西。
但是,我需要做的就是传递特定的二进制数据,其余的由设备处理。
数据必须是二进制格式,我在互联网上看到过各种方法,但真的不确定什么是表示二进制数据而不是字符串的正确方法。
以下是我发现的一些示例:
b'01001011' # Is this a packed string though?
bytes(4) # This creates bytes. How do I manipulate the bits?, is this data able to send over serial?
int('01001011', 2) # Will this be treated as an integer over serial?
binascii.hexify() # This produces ASCII representation
我需要制定几个字节的信息,这将涉及我在每个字节中设置某些位,我很困惑如何去做
python 中的二进制文字如下所示:
>>> 0b11
3
>>> 0b10
2
>>> 0b100
4
您可以使用按位运算符操作位:
>>> 0b1000
8
>>> 0b1000 | 0b1
9
|
只是 or
运算符。在此处查看其他运算符:BitwiseOperators
要查看数字的二进制表示,您可以使用 string.format:
>>> "{0:b}".format(9)
'1001'
>>> "{0:b}".format(65)
'1000001'
>>> "{0:b}".format(234)
'11101010'
编辑 设置特定位的示例:
# setting off second bit
>>> bin(0b1100 & 0b1011)
'0b1000'
# setting on third bit
>>> bin(0b1100 | 0b0010)
0b1110'
请注意二进制字面值给你一个 int:
>>> type(0b1)
<type 'int'>