【问题标题】:Forming bytes bit by bit and concatenating bytes逐位形成字节并连接字节
【发布时间】:2015-03-05 20:12:51
【问题描述】:

我正在尝试通过 TCP 套接字发送字节消息。我有一个静态字节,即十六进制字0xaa。在静态字节上,我需要连接 MSB 始终为 0 的动态字节,然后我有 6-4 的位是可变的(从 000 到 100),而 3-0 的位也是可变的(从 0000 - 1000)。做这个的最好方式是什么?我已经看到我可以使用bitstring 中的bitarrayBitArray 类,但我想知道这个问题的最佳解决方案是什么。另外我需要知道如何将位数组转换回字节,以便我可以通过 TCP 发送它。

我需要的示例:

leading_byte = 0xaa
bit7 = 0 (bit)

options = { 'a' : 000 (bits), 'b' : 001 ...}
versions = { 'i' : 0000 (bits), 'i' : 0001 ...} 
bits6_4 = options['a']
bits3_0 = versions['i']

byte_message = leading_byte + bit7 + bit6_4 + bits3_0

socket.send(byte_message)

【问题讨论】:

    标签: python arrays bit bitarray


    【解决方案1】:

    使用位移和普通chr:

    byte_message = chr(0xaa) + chr((bits6_4 << 4) | bits3_0)
    

    【讨论】:

    • 谢谢!但是如何在 Python 中将 bits6_4 作为 3 位值,或将 bit7 作为信号位?
    • @user3599280:这可以使用逻辑反转的东西来完成——ord() 函数使用&amp; 运算符应用位掩码并朝相反方向移动。
    • 谢谢。我发现这个解决方案更容易。 leading_byte = bytes((0xaa,)) snd = '0' + string_opttion['a'] + string_version['b'] second_byte = bitarray(snd) msg = leading_byte + second_byte.tobytes()
    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 2015-07-02
    相关资源
    最近更新 更多