2016-11-07 64 views
0

嗨我需要在Assembly GAS中開發十六進制數轉換爲二進制數。現在我有這個:裝配GAS轉換器十六進制的二進制

.align 32 

SYSEXIT = 1 
SYSREAD = 3 
SYSWRITE = 4 
STDOUT = 1 
EXIT_SUCCESS = 0 
Input_SIZE = 10 

.bss 
.lcomm Input, Input_SIZE 

.data 

msg: .ascii "Give hex number:\n" 
msg_len = . - msg 

newline: .ascii "\n" 
    newline_len = . - newline 

.text 
.global _start 

_start: 

mov $SYSWRITE, %eax 
mov $STDOUT, %ebx 
mov $msg, %ecx 
mov $msg_len, %edx 
int $0x80 

mov $SYSREAD, %eax 
mov $STDOUT, %ebx 
mov $Input, %ecx 
mov $Input_SIZE, %edx 
int $0x80 

    movl %eax, %edi 
    movl %eax, %edx  
    dec %edx 


loop1: 
cmpl $1, %edx 
je loop1_exit 
movb Input(,%edx,1), %al 


      cmpb 0x00, %al 
      jl number 
      cmpb 0x41, %al 
      jg big_char 
      cmpb 0x46, %al 
      jl big_char 
      cmpb 0x61, %al 
      jg low_char 
      cmpb 0x66, %al 
      jl low_char 

jmp loop1 

number: 
    sub $'0', %al 
big_char: 
    cmpb $'a', %al 
    jae low_char 
    sub $'A', %al 
    add $10, %al 

low_char: 
    sub $'a', %al 
    add $10, %al 

loop1_exit: 
movl $SYSWRITE, %eax 
    movl $STDOUT, %ebx 
    movl $newline, %ecx 
    movl $newline_len, %edx 
    int $0x80 


    movl $SYSEXIT, %eax 
    movl $EXIT_SUCCESS, %ebx 
    int $0x80 

我沒有拉力賽的想法下一步該怎麼做。如何在程序中打印我的二進制數字。我想我需要一些第二個循環打印每個二進制四。這是我現在擁有的可以嗎?

回答

0

這就是我現在擁有的可以嗎?在調試器

運行它,並嘗試不同的輸入,看是否導致CPU的狀態是如你預期它(我有某種懷疑這將是你不指望什麼和一些修改代碼將遵循) 。

如何在程序中打印我的二進制數。

對於數字123450x3039)二進制輸出是11000000111001。又怎樣?

(init部分)假設您在某個寄存器r1中有價值。設置一些其他寄存器r2爲零,除了最高位,對於32b數字r2 = 0x80000000。

to_binary_loop: 
    test r1,r2 ; does bitwise AND, discards result, sets up flags 
    output(zero_flag ? '0' : '1') 
    shr r2,1 ; moves the bit to right by 1 position 
    jnz to_binary_loop ; loop till all bits were processed 

這將顯示全32b二進制輸出的初始值爲零,如00000000000000000011000000111001。爲了避免這種情況,你可能想要把另一個循環提前第一個:

to_binary_skip_leading_zeroes: 
    test r1,r2 
    jnz to_binary_found_leading_one 
    shr r2,1 ; next bit 
    jnz to_binary_skip_leading_zeroes 
    ; no "1" bit found in r1, enforce at least single 0 to display 
    mov r2,1 
to_binary_found_leading_one: 

output(zero_flag ? '0' : '1') ..我會親自寫爲:

; somewhere defined (can be even in .text near the loop, read-only usage) 
bin_digit: .ascii "01" 

    ; in init of loop 
    xor r3,r3 ; pick one of eax,ebx,ecx,edx (spare one), set to zero 

    ; during loop after "test r1,r2" 
    setnz r3_byte_part 
    mov bin_digit(r3),al ; al = '0' (ZF=1) or '1' (ZF=0) 
    ; output char in "al" 

對任何指令根據需要添加大小後綴,我不會用AT & T語法來折磨自己。