當你輸入號碼或想要打印它,你需要轉換到/從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