英文:
How to make a cyclic reset of a byte through zero by sum?
问题
I created bytes. Also I try to make addition of bytes. But I am getting an error
ValueError: byte must be in range(0, 256)
Instead of an error, I expect a loop, for example 255+2 = 1. How can I do it like in C?
bytes_ = bytearray([0xFF, 0xFF, 0xFF])
bytes_[0] = bytes_[0] + 1
bytes_[1] = bytes_[1] + 2
bytes_[2] = bytes_[2] + 3
print(bytes_)
英文:
I created bytes. Also I try to make addition of bytes. But I am getting an error
ValueError: byte must be in range(0, 256)
Instead of an error, I expect a loop, for example 255+2 = 1. How can I do it like in C?
bytes_ = bytearray([0xFF, 0xFF, 0xFF])
bytes_[0] = bytes_[0] + 1
bytes_[1] = bytes_[1] + 2
bytes_[2] = bytes_[2] + 3
print(bytes_)
答案1
得分: 0
通常,添加操作依赖于使用 CPU 寄存器中的进位标志进行位加法。多余的位会被跳过(该值可以在进位标志中看到),比如在一个 8 位寄存器中,只表示数字 0 到 255。请查看这里以获取一些内部信息。
Python 字节不像 CPU 寄存器那样工作。
以下是至少在一个字节中执行的操作:
byte = 0xF9
for i in range(10):
byte = (byte + 1) & 255
print(byte)
通常,您使用整数算术进行加法操作,并通过使用按位与运算来截断所有多余的位数:& 255
。
输出:
250
251
252
253
254
255
0
1
2
3
您的示例修改如下:
bytes_ = bytearray([0xF9])
for i in range(10):
bytes_[0] = (bytes_[0] + 1) & 255
print(bytes_[0])
输出结果相同。
英文:
Usually adding relies on bitwise addition of the bits using the carry flag in a register of the CPU. The excessive bits are skipped (the value can be seen in the carry flag) say in an 8 bit register, so only the numbers 0 to 255 are represented. See here for some internals.
Python bytes don't work like a CPU register.
This is what at least "cyles" through a byte:
byte=0xF9
for i in range(10):
byte = (byte+1) & 255
print(byte)
You normally add, using integer arithmetics and cut off all excessive bits by using a bitwise AND: & 255
.
Output:
250
251
252
253
254
255
0
1
2
3
Your example modified:
bytes_ = bytearray([0xF9])
for i in range(10):
bytes_[0] = (bytes_[0] + 1) & 255
print(bytes_[0])
Gives the same output.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论