Creating an x86 assembler program that converts an integer to a 16-bit binary string of 0's and 1's

前端 未结 2 1692
逝去的感伤
逝去的感伤 2020-12-12 03:52

As the question suggests, I have to write a MASM program to convert an integer to binary. I have tried many different approaches, but none of them helped me at all. The fina

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 04:50

    Next is an example of using "atoi" to convert the string to number, then use assembly to convert the number to binary:

    #include "stdafx.h"
    #include 
    using namespace std;
    int _tmain(int argc, _TCHAR* argv[])
    {   char str[6]; // ◄■■ NUMBER IN STRING FORMAT.
        int num;    // ◄■■ NUMBER IN NUMERIC FORMAT.
        char bin[33] = "                                "; // ◄■■ BUFFER FOR ONES AND ZEROES.
        cout << "Enter a number: ";
        cin >> str;  // ◄■■ CAPTURE NUMBER AS STRING.
        num = atoi(str); // ◄■■ CONVERT STRING TO NUMBER.
        __asm { 
               mov eax, num   // ◄■■ THE NUMBER.
               lea edi, bin   // ◄■■ POINT TO VARIABLE "BIN".
               mov ecx, 32    // ◄■■ NUMBER IS 32 BITS.
            conversion:
                shl eax, 1     // ◄■■ GET LEFTMOST BIT.
                jc  bit1       // ◄■■ IF EXTRACTED BIT == 1
                mov [edi], '0'
                jmp skip
            bit1:
                mov [edi], '1'
            skip :
                inc edi   // ◄■■ NEXT POSITION IN "BIN".
                loop conversion
        }
        cout << bin;
        return 0;
    }
    

提交回复
热议问题