当你输入号码或想要打印它,你需要转换到/从ASCII所以你说得对,减去48
现在,如果用户输入类似“123”你不能只是减去。您需要:
现在想想。 “123”居然1*100+2*10+3
是这样的伪代码将是:
A = readNumber
exp = 10^A.length
result = 0
for i = 0, i < A.length, i++ do
result += A[i]*exp
exp /= 10
end
在汇编语言中它会是这样的:
mov ah, 0Ah
mov dx, offset number
int 21h
; now number[1] index holds total read characters including RET
mov cx, number[1]
dec cx ; we need length without RET
mov ax, 10
.makeExponent:
mul 10 ; MUL multiplies AX with an argument and stores in AX if argument is byte sized
loop .makeExponent
; now CX = 0, AX = exponent
mov dx, ax ; Store exponent in DX
mov cx, number[1] ;CX = digit count again
mov si, offset number
inc si
inc si ; SI shows into number[0], we need to show for number[2] for the first digit
cld ; lodsb instruction does INC SI if DF=0. CLD makes DF=0
xor ax, ax ; AX = 0
xor bx, bx ; BX = 0, BX will be result
.decode
lodsb ;Load value from DS:SI into AL and increment SI
sub ax, 48 ; ASCII->number
mul dx ; Multiply by exponent. Like in 123 case here 1*100, next loop 2*10, then 3*1
add bx, dx ; Add what we've got to result. For 123 case it's 100+20+3
mov ax, dx ; DIV and MUL work only for AX, so move exponent to AX
div 10 ; divide it by 10(100, then 10, then 1)
xchg dx, ax ; And exchange DX and AX values
loop .decode
; BX is your result
现在我还没有在汇编语言等等一些东西,而编码可能会关闭,如: 我假设mul dx
在DX中存储结果的最低位,所以我将DX添加到BX。您可能需要将AX值添加到BX。 DIV也是如此。
也xor val, val
意味着val = 0.这是很久以前比mov val, 0
快现在我只是喜欢它。
什么是“十进制数”?什么是“二进制数”?你手上的手指数是十进制还是二进制? – 2014-10-04 16:28:58