assembly - 如何将负整数转换为字符串并在 MASM 程序集中输出
问题描述
我应该从用户那里获取有符号整数,计算输入数字的总和,然后显示平均值。问题是,负数似乎没有正确显示,尽管我知道总和和平均值计算正确。
为了正确显示负数,我需要在我的程序中添加什么内容?
.
.
.
writeVal PROC USES eax
LOCAL resultString[11]:BYTE
lea eax, resultString
push eax
push [ebp + 8]
call intToStr
lea eax, resultString
displayString eax ; print num
ret 4
writeVal ENDP
intToStr PROC USES eax ebx ecx
LOCAL tempChar:DWORD
mov eax, [ebp + 8]
mov ebx, 10
mov ecx, 0
cld
divideByTen:
cdq
idiv ebx
push edx
inc ecx
cmp eax, 0
jne divideByTen
mov edi, [ebp + 12] ; move into dest array
jmp storeChar
;store char in array
storeChar:
pop tempChar
mov al, BYTE PTR tempChar
add al, 48
stosb
loop storeChar
mov al, 0
stosb
ret 8
intToStr ENDP
.
.
.
解决方案
You can simply check if the number is less than zero and then use neg
instruction to negate it and apply the negative sign -
to the resultString
buffer:
Code for writeVal
will be:
writeVal PROC USES eax ecx edi
LOCAL resultString[11]:BYTE
lea eax, resultString
mov ecx, [ebp + 8] ; load passed number to ebx
test ecx, ecx ; test number to see if it's less than zero
jnl non_negative ; jump if not less to non_negative
neg ecx ; else we have a negative number so neg to make it positive
mov byte ptr [eax], '-' ; set resultString[0] to '-'
inc eax ; increase resultString ptr + 1
non_negative:
push eax ; push the resultString + 1
push ecx ; push the number
call intToStr ; convert the number
lea eax, resultString
printc eax ; print num
ret 4
writeVal ENDP
Compile and run:
start:
push -14286754
call writeVal
exit
end start
Will print:
-14286754
推荐阅读
- python - 以整数为参数并返回对应月份和年份的函数
- kubernetes - 我在部署 pod 时收到错误“networkPlugin cni failed to setup pod”
- android - 如何将 alac 解码器注册到多媒体框架?
- javascript - 重新渲染页面以可视化快速排序?
- java - 如何在 Java 单元测试中模拟“无法访问 Internet”以测试 liquibase 迁移
- c# - 从列表列表中选择一个元素
- angular - Storybook Angualr 和 ng-bootstrap
- json - 将 XAMPP shell 添加到新的“Windows 终端”
- mysql - Laravel WHERE 对 NULL 列的查询不起作用。漏洞?
- javascript - 如何使用 jQuery 过滤数据表的年份和月份?