2015-11-25 123 views
0

我想在C++中得到這個動作的彙編代碼版本。我做了下面的代碼。使用索引從字符串中選擇單個字符?

#include <iostream> 
#include <string> 
#include <cstdlib> 
#include <random> 
using namespace std; 

void RandomizeData(); 

string vowel = "AEIOU"; 
string consonant = "BCDFGHJKLMNPQRSTVWXYZ"; 
int Matrixes = 0; 
int Rows = 0; 
int Characters = 0; 
int test; 

int main() 
{ 
    // declare variables 

    while (Matrixes < 4) 
    { 
     while (Rows < 4) 
     { 
      while (Characters < 4) 
      { 
       RandomizeData(); 
       ++Characters; 
      } 
      Characters = 0; 
      Rows++; 
      cout << "\n"; 
     } 
     Rows = 0; 
     Characters = 0; 
     cout << "\n\n"; 
     ++Matrixes; 
    } 

    cin >> test; 

    return 0; 
} 

void RandomizeData() 
{ 
    int randVowel = (rand() % 5); 
    int randCons = (rand() % 21); 

    test = (rand() % 2); 

    if (test == 1) 
    { 
     cout << consonant[randCons] << ""; 
    } 
    else 
    { 
     cout << vowel[randVowel] << ""; 
    } 
} 

我已經爲asm做了一切實際操作。但是,我仍然無法讓這部分工作或翻譯它。

 ;How to do the following in asm? 
     cout << consonant[randCons] << ""; 

以下是我到目前爲止: !!警告!代碼不好!

INCLUDE Irvine32.inc 

.386 
.stack 4096 
ExitProcess proto,dwExitCode:dword 


    .data 

     vowels DB "AEIOU" 
     cons DB "BCDFGHJKLMNPQRSTVWXYZ", 0 
     path DWORD 0 
     cool BYTE ?         ;determines vowel or cons 

     ;Loop counters 
     rows DWORD 0 
     matrixes DWORD 0 
     characters DWORD 0 

     ;Random variables 
     rndVowel  DWORD ? 
     rndCons  DWORD ? 



    .code 
     main PROC 
      STEP1: cmp  matrixes, 4 
        jge  STEP4 

      STEP2: cmp  rows, 4 
        jge  STEP1 
        mov  characters, 0 

      STEP3: cmp  characters, 4 
        jge  STEP2 
        call CharSelector    ;get & display character 
        inc  characters    
        jmp  STEP3      ;repeat STEP 3 

      STEP4: invoke ExitProcess,0 
     main ENDP 




     CharSelector PROC 
      call Randomize       ;seed 
      mov  eax, 2 
      call RandomRange 
      mov  path, eax       ;mov result to path 

      STEP1: cmp  path, 1 
        mov  ecx, 0 
        jne  STEP2 

      STEP2:          ;block chooses vowel index         
        mov  eax, 5 
        call RandomRange 
        mov  rndVowel, eax 


        ;How to do the following in asm 


        call WriteString 


        exit 

      STEP3:          ;block chooses cons index 
        mov  eax, 21 
        call RandomRange 
        mov  rndCons, eax 
        exit 
     CharSelector ENDP 


    end main 
+2

爲什麼你想這樣做,擺在首位?另外,您是在編譯32位還是64位模式? –

+1

如果您想要某種方式的示例,您可以隨時查看編譯器輸出。只要你理解它,這是學習ASM的好方法。 –

回答

1

這些字符每個都是一個字節,所以只需使用索引來偏移數組的基地址。

好像你有你在eax(從RandomRange的返回值)指數,所以你應該能夠做到例如: -

mov bl, [cons + eax] ; read the character at index eax in cons, and place it in register bl 
+0

謝謝,它的工作原理。我仍然無法正確理解如何使用寄存器。 –