0

I am very new in nasm assembly, so I apologize if this was a really noob question. This is what I've got so far.

%include    'functions.asm'

section .data
    ip_prompt   db  "Enter a decimal number to be converted to binary: ", 0h
    binary_res  db  32 dup('0')

section .bss
    dec_input resb 32    

section .text
    global _start
    
_start:
    mov     eax, ip_prompt
    call    str_print

    mov     eax, SYS_READ
    mov     ebx, STDIN
    mov     ecx, dec_input
    mov     edx, 32
    int     80h

    mov     eax, dec_input
    call    str_print

    mov ecx, 0
    mov eax, dec_input
    mov ebx, 2
    xor edx, edx

convert_to_bin:
    div     ebx
    mov     [binary_res + ecx], edx
    inc     ecx
    cmp     eax, 0
    jne     convert_to_bin

    mov     eax, binary_res
    call    str_print_endl

    call    quit

I am trying to implement the continuous division method by dividing the dec_input into 2 until it reaches 0. But after running the program, it outputs Segmentation fault (core dumped).

ciao
  • 1
  • 1
    `read()` system call reads bytes, not a null-terminated string. Assuming `print_str` expect string, you should set null byte to the end according to value returned by `read()`. Then, `dec_input` contans characters, not a number. You should convert decimal string to a number first, then convert number to binary string. Also you can use `shr` for division by 2 instead of `div`. Carry flag will contain reminder. – dimich May 03 '23 at 02:07
  • Using `div` that way will produce the least-significant digit as the remainder and move the others down. So you're storing it backwards in your buffer. For base 10, see [How do I print an integer in asm without printf from the c library?)](https://stackoverflow.com/a/46301894), but base 2 (or any power of 2) on a binary computer allows peeling off digits in the other direction, starting with the MSD (first in printing order). As in [How to convert a binary integer number to a hex string?](https://stackoverflow.com/q/53823756) but base2 is even easier, often using the carry flag. – Peter Cordes May 03 '23 at 02:45
  • For working code, see [Creating an x86 assembler program that converts an integer to a 16-bit binary string of 0's and 1's](https://stackoverflow.com/a/40811986) (and my answer for an SSE2 version). – Peter Cordes May 03 '23 at 02:53

0 Answers0