在机器代码中区分有符号和无符号 [英] distinguishes between signed and unsigned in machine code

查看:42
本文介绍了在机器代码中区分有符号和无符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读一本教科书说:

重要的是要注意机器代码如何区分签名和无符号值.与 C 不同,它不关联数据类型与每个程序值.相反,它主要使用相同的两种情况的(汇编)指令,因为许多算术对于无符号和无符号操作具有相同的位级行为补码运算.

It is important to note how machine code distinguishes between signed and unsigned values. Unlike in C, it does not associate a data type with each program value. Instead, it mostly uses the same (assembly)instructions for the two cases, because many arithmetic operations have the same bit-level behavior for unsigned and two’s-complement arithmetic.

我不明白这是什么意思,谁能给我举个例子?

I don't understand what it means, could anyone provide me an example?

推荐答案

例如这段代码:

int main() {
    int i = -1;
    if(i < 9)
        i++;
    unsigned u = -1;  // Wraps around to UINT_MAX value
    if(u < 9)
        u++;
}

在 x86 GCC 上给出以下输出:

gives following output on x86 GCC:

main:
    push    rbp
    mov     rbp, rsp
    mov     DWORD PTR [rbp-4], -1 ; i = -1
    cmp     DWORD PTR [rbp-4], 8  ; i comparison
    jg      .L2                   ; i comparison
    add     DWORD PTR [rbp-4], 1  ; i addition
.L2:
    mov     DWORD PTR [rbp-8], -1 ; u = -1
    cmp     DWORD PTR [rbp-8], 8  ; u comparison
    ja      .L3                   ; u comparison
    add     DWORD PTR [rbp-8], 1  ; u addition
.L3:
    mov     eax, 0
    pop     rbp
    ret

注意它如何对变量 iu<使用相同的初始化(mov)和增量(add)指令/代码>.这是因为无符号和 2 的补码的位模式变化相同.

Notice how it uses the same instructions on intialization (mov) and increment (add) for variables i and u. This is because the bit pattern changes identically for unsigned and 2's complement.

比较也使用相同的指令cmp,但跳转决策必须不同,因为设置最高位的值在类型上是不同的:jg(跳转如果更大)在有符号上,ja(在上面跳转)在无符号上.

Comparison also uses the same instruction cmp, but jump decision has to be different, because values where the highest bit is set are different on the types: jg (jump if greater) on signed, and ja (jump if above) on unsigned.

选择什么指令,取决于架构和编译器.

What instructions are chosen, depends on the architecture and the compiler.

这篇关于在机器代码中区分有符号和无符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆