打印有符号整数优化 [英] printing a signed integer optimization

查看:35
本文介绍了打印有符号整数优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Igor Zhirkov 的著作 Low-Level Programming 中有这个未解决的问题:

There's this unanswered question in the Igor Zhirkov's book Low-Level Programming :

"尝试在不调用print_uint、复制其代码或使用jmp的情况下重写print_int.你会只需要一条指令和仔细的代码放置.

"Try to rewrite print_int without calling print_uint, copying its code, or using jmp. You will only need one instruction and a careful code placement.

阅读关于协程的内容.".

Read about co-routines.".

为print_int"提供的代码和print_uint":

The supplied code for "print_int" and "print_uint":

print_uint:
    mov rax, rdi
    mov rdi, rsp
    push 0
    sub rsp, 16
    
    dec rdi
    mov r8, 10

.loop:
    xor rdx, rdx
    div r8
    or  dl, 0x30
    dec rdi       
    mov [rdi], dl
    test rax, rax
    jnz .loop 
   
    call print_string
    
    add rsp, 24
    ret

print_int:
    test rdi, rdi
    jns print_uint
    push rdi
    mov rdi, '-'
    call print_char
    pop rdi
    neg rdi
    jmp print_uint

print_char:
    push rdi
    mov rdi, rsp
    call print_string 
    pop rdi
    ret
print_string:
    push rdi
    call string_length
    pop rsi
    mov rdx, rax
    mov rax, 1
    mov rdi, 1
    syscall
    ret

他说的那个特殊的单一指令是什么?

What could be that special single instruction he's talking about ?

推荐答案

很抱歉,很遗憾这是一个错误.

I am so sorry, but it is unfortunately an error.

有一对函数print_newlineprint_char,其中print_newline可以表示为一个指令,如果控制落到print_char 之后.我写了一篇关于它的博文.基本思想是打印特定字符,即换行符就像开始打印任何字符"一样.子程序,当它的参数被赋值为所述字符的代码时.

There is a pair of functions print_newline and print_char where print_newline can be expressed as one instruction if the control falls to print_char afterwards. I wrote a blog post about it. The basic idea is that printing a specific character i.e. the newline feed is like starting the "print any character" subroutine when its argument is assigned the code of the said character.

print_newline:
   mov rdi, '\n'  ; first integer argument is in rdi
print_char:
   ...

至于 print_int 我敢肯定,在 AMD64 上你不能通过一条指令来表达它并落入 print_uint.

As to print_int I am sure that on AMD64 you can not express it through one instruction and fall to print_uint.

这篇关于打印有符号整数优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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