简体   繁体   English

Python 带负字节的字节数组

[英]Python bytearray with negative bytes

I don't know anything about bytes.我对字节一无所知。 But, I have a Java application which I've developed to talk to my E-scooter.但是,我有一个 Java 应用程序,我开发了它来与我的电动滑板车交谈。

I'm trying to write something similar on a Raspberry Pi, so I use Python.我正在尝试在 Raspberry Pi 上编写类似的东西,所以我使用 Python。 In the Java application, I have byte arrays that have negative numbers.在 Java 应用程序中,我有字节 arrays 有负数。 For example:例如:

byte[] array = new byte[90, -91, 0, 118, 57, 11...];

In Python, I get a "byte must be in range(0, 256) when trying to do this:在 Python 中,尝试执行此操作时,我得到一个“字节必须在范围内(0, 256):

array = bytearray([90, -91, 0, 118, 57, 11...])

Anyone who could help?有谁能帮忙吗? Thanks in advance.提前致谢。

Maybe you can try -91 + 256 instead of -91, the binary code is same.也许你可以试试 -91 + 256 而不是 -91,二进制代码是一样的。

use (a + 256) % 256 to change negative to postive number.使用 (a + 256) % 256 将负数变为正数。

-91 and 165 in 8 bit are the same in binary representation. 8 位中的 -91 和 165 在二进制表示中是相同的。 [1010 0101] [1010 0101]

array = bytearray([90, 165, 0, 118, 57, 11...])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python 2.6 和 3 中的字节与字节数组 - bytes vs bytearray in Python 2.6 and 3 树莓派上的“ValueError:负数返回字节(bytearray(seq))” - “ValueError: negative count return bytes(bytearray(seq))” on raspberry pi 在python中的十六进制字节数组中交换字节对 - Swap pairs of bytes in a hex bytearray in python Python: TypeError: str, bytes or bytearray expected, not int - Python: TypeError: str, bytes or bytearray expected, not int 如何在 Python 3.7 中向 bytearray 添加字节? - How to add bytes to bytearray in Python 3.7? Python:bytearray对象的长度与派生字节对象的长度不匹配吗? - Python: The length of bytearray object does not match the length of derived bytes object? 将Python中的字节从Numpy数组复制到字符串或字节数组 - Copying bytes in Python from Numpy array into string or bytearray 为什么Python中的bytearray函数将一个字节变成两个字节? - Why does bytearray function in Python turn one byte into two bytes? Python 3 类型错误:JSON object 必须是 str、bytes 或 bytearray,而不是 Tag - Python 3 TypeError: the JSON object must be str, bytes or bytearray, not Tag Python 不正确的 AES 密钥长度尽管传递了一个 32 字节的字节数组 - Python Incorrect AES key length despite passing the a 32 bytes bytearray
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM