如何通过求和实现字节的循环零复位?

huangapple go评论105阅读模式
英文:

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?

  1. bytes_ = bytearray([0xFF, 0xFF, 0xFF])
  2. bytes_[0] = bytes_[0] + 1
  3. bytes_[1] = bytes_[1] + 2
  4. bytes_[2] = bytes_[2] + 3
  5. 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?

  1. bytes_ = bytearray([0xFF, 0xFF, 0xFF])
  2. bytes_[0] = bytes_[0] + 1
  3. bytes_[1] = bytes_[1] + 2
  4. bytes_[2] = bytes_[2] + 3
  5. print(bytes_)

答案1

得分: 0

通常,添加操作依赖于使用 CPU 寄存器中的进位标志进行位加法。多余的位会被跳过(该值可以在进位标志中看到),比如在一个 8 位寄存器中,只表示数字 0 到 255。请查看这里以获取一些内部信息。

Python 字节不像 CPU 寄存器那样工作。

以下是至少在一个字节中执行的操作:

  1. byte = 0xF9
  2. for i in range(10):
  3. byte = (byte + 1) & 255
  4. print(byte)

通常,您使用整数算术进行加法操作,并通过使用按位与运算来截断所有多余的位数:& 255

输出:

  1. 250
  2. 251
  3. 252
  4. 253
  5. 254
  6. 255
  7. 0
  8. 1
  9. 2
  10. 3

您的示例修改如下:

  1. bytes_ = bytearray([0xF9])
  2. for i in range(10):
  3. bytes_[0] = (bytes_[0] + 1) & 255
  4. 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:

  1. byte=0xF9
  2. for i in range(10):
  3. byte = (byte+1) & 255
  4. print(byte)

You normally add, using integer arithmetics and cut off all excessive bits by using a bitwise AND: & 255.

Output:

  1. 250
  2. 251
  3. 252
  4. 253
  5. 254
  6. 255
  7. 0
  8. 1
  9. 2
  10. 3

Your example modified:

  1. bytes_ = bytearray([0xF9])
  2. for i in range(10):
  3. bytes_[0] = (bytes_[0] + 1) & 255
  4. print(bytes_[0])

Gives the same output.

huangapple
  • 本文由 发表于 2023年7月6日 17:08:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定