【发布时间】:2019-04-04 01:22:21
【问题描述】:
我在 AT&T 64 位汇编中实现了一个旋转功能,并且在我的代码中无法获得正确的输出。
我要实现的功能是
unsigned long rotate(unsigned long val, ul num, ul dir);
Val 是我想要旋转的值,num 是多少次,方向是左还是右,0 是右,1 是左。
我的汇编代码:
.global rotate
rotate: #value = %rdi
#num = %rsi
#direction = %rdx
mov %rsi, %r10 #puts num into register
test %rdx, %rdx
jz right #if rdx is 0 jump to rotate right
#else go to loop right below which rotates left
loop:
test %r10, %r10 #if num is 0 I am done
jz done
rol $1, %rdi #rotate left 1 bit
dec %r10 #decrement my count
jmp loop #jump to top of loop
right: #same logic as left
test %r10, %10
jz done
rol $1, %rdi
dec %r10
jmp loop
done:
mov %rdi, %rax
ret
我的 C 代码:
#include <stdio.h>
extern unsigned long rotate(unsigned long val, unsigned long num, unsigned long direction);
int main()
{
unsigned long v,n,d;
v = 0xDEADBEEFDEADBEEF;
n = 2;
d = 1;
printf("%x\n ", rotate(v,n,d));
}
当我编译和运行时,我得到了值0x7AB6FBBF,而我应该得到0x7AB6FBBF7AB6FBBF。
我的指令没有发送unsigned longs 或其他什么有问题吗?
【问题讨论】:
-
那不应该是一个无符号长长吗?
-
你知道在大多数平台上
long是 32 位的,对吧? -
@Sneftel:x86-64 System V 具有 64 位
long,并且此代码在 RDI 和 RSI 中采用 args,因此它绝对是 ABI。 (Where is the x86-64 System V ABI documented?) -
我把c代码改成全无符号长整数,结果都一样
-
@pigsploof: x86 有
rol %cl, %rdi和ror %cl, %rdi,您可以使用它们来代替循环。只需将mov您的班次计入%ecx。