gpt4 book ai didi

loops - 汇编循环遍历寄存器值的每一位

转载 作者:行者123 更新时间:2023-12-04 12:50:20 24 4
gpt4 key购买 nike

我有一个寄存器 $t0,其中存储了一些整数。例如,假设我将整数 1100 存储到其中。这个值的二进制表示是 0000010001001100。当然对于 32 位寄存器它可以扩展到 32 位,但这很容易做到。

我正在尝试在程序集中实现一个循环,该循环遍历寄存器值的每一位并检查它是 1 还是 0。该怎么做?

也许我误解了寄存器的性质。据我了解,寄存器存储一个 32 位数字,是吗?这是否意味着每一位都存储在特定地址?

我曾尝试对寄存器使用移位并检查位,但失败了。我还查看了 lb 命令,但这会加载字节,而不是位。那么一个人会做什么呢?

最佳答案

一些基础知识:

大多数(全部?)移位指令将位移出进位标志

大多数(所有?)CPU 都有一个分支命令,可以跳转到设置了进位标志的位置

结合这一点,您可以执行以下操作:

load register1,< the value to be tested >
load register2, 0

Lrepeat:
compare register1 with 0
jump if zero Lexit

shift right register1
jump no carry Lskip
increase register2
Lskip:
jump Lrepeat

Lexit: ; when you end up here, your register2
; holds the count of bit register1 had set

仍然可以进行一些优化:

Lrepeat:
compare register1 with 0
jump if zero Lexit
shift right register1
jump no carry Lskip <-- note: here you jump ...
increase register2
Lskip:
jump Lrepeat <-- ... to jump again!
Lexit:

=====>

Lrepeat:
compare register1 with 0
jump if zero Lexit
shift right register1
jump no carry Lrepeat <-- so you can optimize it this way
increase register2
Lskip:
jump Lrepeat
Lexit:

有些 CPU 有“加进位”指令,例如6502:

ADC register,value      ; register = register + value + Carry flag

这可以用来避免分支(条件跳转),方法是在每个循环中将 0(当然加上进位)添加到 register2

    shift right register1
add with carry register2,0 ; may look weird, but this adds a
; 1 if the carry is set, which is
; exactly what we want here
jump Lrepeat

请注意,您不需要知道寄存器大小!您只需循环直到寄存器为 1,这可以为您节省很多时间,例如如果您的值类似于 0000 0000 0000 0000 0000 0000 0001 1001

关于loops - 汇编循环遍历寄存器值的每一位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39823867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com