我一直在玩x87 FPU编程,我刚刚遇到了从浮点(32位)到int (32位)转换的魔法咒语:
flds from # number to convert from
fadds magic1 # add magic number 1 (???)
fstps to # store in destination as single-precision binary32
movl to,%eax # load float result as an int
subl $magic2,%eax # subtract magic number 2 (???)
sarl $1,%eax # divide by 2
movl %eax,to # and look, here's the result!
.section .rodata
magic1: .float 6291456.0 # 3 * 2^21
.equ magic2, 0x4ac00000 # ???
.data
from: .float 31415.9265 # pick a number, any number...
to: .long 0 # result ends up here(AT&T语法与GAS指令)
我已经尝试过了,而且它看起来很有效(-infinity的四舍五入),但是我完全不知道为什么!有人能解释一下它的工作原理吗?
发布于 2022-02-25 13:37:30
快速回答:
第一个神奇的数字强制重新调整参数的标度,这样整数部分的LSbit就变成了分数中最右边的,但却是一个。
然后添加第二个魔法将删除指数位。
关于最后一次除以2 IDK的必要性,必须有额外的技术性(可能与添加3.2^21而不是1.2^21有关)。
https://stackoverflow.com/questions/69030824
复制相似问题