gpt4 book ai didi

linux - 在汇编中查找数字是偶数/奇数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:55 26 4
gpt4 key购买 nike

我正在尝试查找给定数字(用户输入)是偶数还是奇数。

I'm simply applying AND operation on binary digits of a no. with 1, If the number is odd then operation will result 0 and we will Output Number is odd, otherwise we will output Number is even.

虽然逻辑看似简单,但在下面的代码中却行不通。我不知道代码中的问题在哪里。谁能告诉我问题出在哪里

section .data
userMsg db 'Please enter a number'
lenuserMsg equ $ - userMsg
even_msg db 'Even Number!'
len1 equ $ - even_msg
odd_msg db 'Odd Number!'
len2 equ $ - odd_msg

section .bss
num resb 5 ;Reserved 5 Bytes for Input

section .text

global _start ;must be declared for linker (gcc)

_start:
;User Prompt
mov ebx, 1 ;file descriptor (stdout)
mov ecx, userMsg ;message to write 'Please enter a number'
mov edx, lenuserMsg ;message length
mov eax, 4 ;system call number (sys_write)
int 0x80 ;call kernel

;Taking user input
mov ebx, 0 ;(stdin)
mov ecx, num
mov edx, 5 ;i/p length
mov eax, 3 ;system call number (sys_read)
int 0x80 ;call kernel

mov ax, [num]
and ax, 1
jz evnn ;Jump on Even

;Printing No. is Odd
mov ebx, 1 ;file descriptor (stdout)
mov ecx, odd_msg ;message to write 'Odd Number!'
mov edx, len2 ;message length
mov eax, 4 ;system call number (sys_write)
int 0x80 ;call kernel
jmp outprog ;Jump to exit

;Printing No. is Even
evnn:
mov ebx, 1 ;file descriptor (stdout)
mov ecx, even_msg ;message to write 'Even Number!'
mov edx, len1 ;message length
mov eax, 4 ;system call number (sys_write)
int 0x80 ;call kernel

;Exit
outprog:
mov eax, 1 ;system call number (sys_exit)
int 0x80 ;call kernel

最佳答案

只关注手头的实际问题,好吗?如果说一个 ASCII 字符被放入 AL 寄存器,只需将其转换为一个数字,其余的应该是自然的。在计算(二进制数和系统)中,整数的奇数或偶数由位0决定。如果为1,则为奇数。如果为0,则为偶数。 (令我惊讶的是,到目前为止还没有人特别强调这一点)。

    ...                  ;OS puts a char in AL.
sub al,30h ;turn an ASCII char to one integer digit
shr al,1 ;Lets see how the flags responds below
jc .odd ;CF is set if the first bit (right-most, bit 0) is 1.
;do Even things
;skip pass .odd
.odd:
;do Odd things

关于linux - 在汇编中查找数字是偶数/奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34834606/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com