[C++] Example codes

Results 1 to 3 of 3
  1. #1

    [C++] Example codes

    //language: C++
    //Random number generator. Will generate as many numbers as needed between min value enter and max value enter including min and max.



    Code:
    #include<iostream>
    #include <ctime>
    #include<cstdlib>
    
    using namespace std;
    
    int main()
    **
    	int max;
    	int min;
    	int rolls;
    	int roll;
    	int count;
    	char z='y';
    
    	while(z=='y')
    	**	
    		cout<<"enter number of rolls"<<endl<<endl;
    		cin>>rolls;
    		srand(time(0));
    
    		cout<<"enter min roll"<<endl<<endl;
    		cin>>min;
    		cout<<"enter max roll"<<endl<<endl;
    		cin>>max;
    		cout<<endl<<endl;
    	
    		max=max-min+1;
    		count=1;
    			
    		while(rolls>0)
    		**
    			roll=(rand() % max) + min;
    			cout<<"roll number "<<count<<":   "<<roll<<endl;
    			roll=0;
    			rolls--;
    			count++;
    		
    		}
    
    	cout<<endl<<endl<<"do you want to roll again(type y or n)"<<endl;
    	cin>>z;
    	
    	}
    	return 1;
    
    
    
    
    }



    Useage:



    Code:
    tgo@localhost:~/asm$ nasm -f elf add.asm
    tgo@localhost:~/asm$ gcc -o add add.o
    tgo@localhost:~/asm$ ./add
    Enter two numbers
    25
    30
    Total of 25 and 30 is 55
    tgo@localhost:~/asm$



    Code:
    [SECTION .text]
    
    extern printf
    extern scanf
    
    global main
    
    main:
    
    	; show input banner
    
    	push dword entermsg
    	call printf
    	add esp,4
    	
    	; get first number with scanf
    	
    	push dword one
    	push dword num
    	call scanf
    	add esp,8
    	
    	; get second number with scanf
    
    	push dword two
    	push dword num
    	call scanf
    	add esp,8
    	
    	; add numbers and store in eax
    	
    	mov eax,[one]
    	add eax,[two]
    		
    	; show total push values for totalmsg to display
    	
    	push eax 
    	push dword [two]
    	push dword [one]
    	push totalmsg
    	call printf
    	add esp,16
    	
    
    [SECTION .bss]
    
    one resd 1
    two resd 1
    
    [SECTION .data]
    
    entermsg db 'Enter two numbers',10,0
    totalmsg db 'Total of %d and %d is %d',10,0
    num db '%d',0
    --------------------------------------------------------------------------------------------------------------------------------


    Code to break Caesars Box encrpytion.


    Code:
     	tgo@localhost:~/perl$ perl cryp.pl HOUIY\!TO\!
    HITOYOU!!
    tgo@localhost:~/perl$ perl cryp.pl hoacfucdoowkach\?wdocwku?mwohoccluoduookacuccduwwhlhkclolwduihdo\!
    howmuchwoodwouldawoodchuckchuckifawoodchuckcouldchuckwood??lawl!
    tgo@localhost:~/perl$
    The first loop finds the perfect square of the number and if it doesnt have one it prints a message and quits.

    For the important part the outer loop loops from 0 to the perfect square. The inner loop goes through the string and grabs inner * perfect square + outer loop. So for instance if we had an easy one like abcdefghi and it just started the loops it would grab 0 * 3 + 0 and take that character which would be a. then it would grab 0 * 3 + 1 which would be d then 0 * 3 + 2 which would be g. and that would be the first row.

    Code:
    #!/usr/bin/perl
    
    ------------------------------------------------------------------------------------------------------------------------------
    
    # Code to break Caesars Box encryption
    # Coded by tgo
    # http://www.anomalous-security.org
    
    use warnings;
    
    if (@ARGV != 1)
    **
    warn("Useage $0 <string>\n");
    exit(1);
    }
    
    $string = $ARGV[0];
    $length = length($string);
    
    for ($x=1;$x<20;$x++)
    **
    	$total = $x * $x;
    		
    	if ($total == $length)
    	**	
    	$num = $x;
    	last;
    	}
    	elsif ($total >= $length)
    	**
    	warn("The length of your string is a not a perfect square\n");
    	exit(1);
    	}
    }

    -----------------------------------------------------------------------------------------------------------------------------


    Very simple Program To Extract Standard ASCII Characters To A File... I
    Used It To Extract Some Text From A File That Was Mostly Junk... Very

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    **
    	FILE *fin, *fout;
    	char *alpha="abcdefghigjlmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890:\n/\\";
    	int input, for_i;
    	
    	
    	if(argc != 3)
    	**
    		printf("Usage: %s <Input Filename> <Output Filename>\n", argv[0]);
    		exit(0);
    	}
    	
    	fin = fopen(argv[1], "rb");
    	fout = fopen(argv[2], "wb");
    	
    	if(fin == NULL)
    	**
    		printf("Error:");
    		perror(fin);
    		exit(0);
    	}
    	
    	if(fout == NULL)
    	**
    		printf("Error:");
    		perror(fout);
    		exit(0);
    	}
    	
    	while(!feof(fin))
    	**
    		input = fgetc(fin);
    		for(for_i = 0; for_i < strlen(alpha); for_i++)
    		**
    			if(input == alpha[for_i])
    			**
    				fputc(input, fout);
    			}
    		}
    	}
    return 0;

    useful


    ------------------------------------------------------------------------------------------------------------------


    // Delphi Code

    // selects 6 random numbers 1-49








    Code:
    // author: Moralterror
    // date: 16/03/05
    // selects 6 random numbers between 1-49
    
    var num: array of integer;
    var    i: integer;
    
    begin
      setLength(num,6);
      num[0] := random(49)+1;
      label1.caption := '';
      label2.caption := '';
      label3.caption := '';
      label4.caption := '';
      label5.caption := '';
      label6.caption :=  '';
    
    
      label1.caption := IntToStr(num[0]);
    
       repeat
        num[1] := random(49)+1;
        if  num[1] <>  num[0] then
          begin
             label2.caption := IntToStr(num[1]);
          end;
        until  label2.caption  > '';
    
      repeat
      num[2] := random(49)+1;
        if  num[1] <>  num[2] then
          begin
            if  num[2] <>  num[0] then
              begin
                label3.caption := IntToStr(num[2]);
              end;
          end;
      until  label3.caption  > '';
    
    
      repeat
      num[3] := random(49)+1;
         if  num[1] <>  num[3] then
          begin
            if  num[3] <>  num[0] then
              begin
                  if  num[3] <>  num[2] then
                    begin
                      label4.caption := IntToStr(num[3]);
                    end;
              end;
          end;
      until  label4.caption  > '';
    
    
      repeat
      num[4] := random(49)+1;
        if  num[1] <>  num[4] then
          begin
            if  num[4] <>  num[0] then
              begin
                  if  num[4] <>  num[2] then
                    begin
                      if  num[4] <>  num[3] then
                         begin
                            label5.caption := IntToStr(num[4]);
                         end;
                    end;
              end;
          end;
       until  label5.caption  > '';
    
    
      repeat
      num[5] := random(49)+1;
        if  num[1] <>  num[5] then
          begin
            if  num[5] <>  num[0] then
              begin
                  if  num[5] <>  num[2] then
                    begin
                      if  num[5] <>  num[3] then
                         begin
                            if  num[5] <>  num[4] then
                              begin
                                label6.caption := IntToStr(num[5]);
                              end;
                         end;
                    end;
              end;
          end;
       until  label6.caption  > '';
    
    end;

    --------------------------------------------------------------------------------------------------------------------------

    Lang: c++

    Desc: Simple download client. The URL, server IP, and output file name is hardcoded - easy enough to change that, though.



    Code:
    #include <windows.h>
    #include <winsock2.h>
    #include <iostream>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    **
    
        // Initialize Winsock.
        WSADATA wsaData;
        int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
        if ( iResult != NO_ERROR )
        **
           cout << "Error at WSAStartup()\n";
           system("PAUSE");
           return 1;
        }
    
        // Create a socket.
        SOCKET m_socket;
        m_socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
    
        if ( m_socket == INVALID_SOCKET )
        **
            cout << "Error at socket(): " << WSAGetLastError();
            WSACleanup();
            system ("PAUSE");
            return 1;
        }
    
        // Connect to a server.
        sockaddr_in clientService;
    
        clientService.sin_family = AF_INET;
        clientService.sin_addr.s_addr = inet_addr( "207.44.154.68" ); // Remote server IP
        clientService.sin_port = htons( 80 );
    
        if ( connect( m_socket, (SOCKADDR*) &clientService,
                      sizeof(clientService) ) == SOCKET_ERROR)
        **
            cout << "Failed to connect.\n";
            WSACleanup();
            system("PAUSE");
            return 1;
        }
    
        // Send and receive data.
        int bytesSent;
        int bytesRecv = SOCKET_ERROR;
        char sendbuf[] = "GET http://files4.rarlab.com/rar/wrar351.exe\n";  // 'GET' request
        char recvbuf[512] = "";
        long int total = 0;
    
        // Send the request.
        bytesSent = send( m_socket, sendbuf, strlen(sendbuf), 0 );
        cout << "Bytes Sent: " << bytesSent << endl;
    
    
        HANDLE hFile;
        DWORD dwBytesWritten;
        // Open a file handle.
        hFile = CreateFile(TEXT("Winrar.exe"),     // file to create
                          GENERIC_WRITE,         // open for writing
                          0,                    // do not share
                          NULL,                  // default security
                          CREATE_ALWAYS,          // overwrite existing
                          FILE_ATTRIBUTE_NORMAL,   // normal file
                          NULL);                  // no attr. template
    
        bool recving = true;
        do
        **
           if (!(bytesRecv == 0) || 
              (bytesRecv == SOCKET_ERROR && WSAGetLastError()== WSAECONNRESET) )
           **
               bytesRecv = recv( m_socket, recvbuf, 512, 0 );  // Receive data
               if ( bytesRecv == -1 )
               **
                  cout << "\nConnection Closed." << endl; 
                  recving = false;
               }
    
               if ( bytesRecv != 0 )
               **
                  recvbuf[bytesRecv] = '\0'; // NULL terminate recvbuf
    
                  // Output last received data chunk to file.
                  WriteFile(hFile,          // handle to the file
                            recvbuf,         // buffer containing the data to be written
                            bytesRecv,        // number of bytes to be written
                            &dwBytesWritten,  // pointer to variable that receives the number of bytes written
                            NULL);          // no OVERLAPPED struct
    
                  total += bytesRecv;
                  system("CLS");
                  cout << "rev: " << total << " Bytes";
               }
           }
           else
           **
                cout << "\n\nDone!\n";
                cout << "\nTotal Bytes recv: " << total << endl;
                CloseHandle(hFile);
                recving = false;
           }
        } while (recving);
    
        system("PAUSE");
        return 0;
    }
    EDIT: For Visual Studio link to: WS2_32.lib
    For Dev-C++ link to: libWS2_32.a



    --------------------------------------------------------------------------------------------------------------------------------


    C/386 Assembly.
    Utility.
    Various general-purpose routines, needs an algorithm update, but usable. Routines are typically 100-600% faster than their C/WinAPI equivilents.

    Utility.cpp
    Code:
    Code:
    /*
     * Utility.cpp
     * ===========
     * Copyright (C) Matthew J. W.
     * All rights reserved.
     * Version 1.0
     *
     *
     * Abstract:
     *   This module covers routines which are of a very general nature, and could
     *   not be categorized any other way.
     *
     *
     *******************************************************************************************************************************************************/
    #include MASTER_INCLUDE
    
    
    
    
    ////////////////////////////////////////////////////////////////////////////
    //
    // Math Functions
    //
    ////////////////////////////////////////////////////////////////////////////
    
    //--------------------------------------------------------------------------
    // Dword PowerOf(Dword, Dword)
    // ===========================
    //
    // Description:
    //   Calculates the power of a base raised to an exponent. 
    //
    //
    // Parameters:
    //   [Dword] [dwBase]     - The base being raised.
    //   [Dword] [dwExponent] - Power the base is being raised to.
    //
    //
    // Return Value:
    //   Returns the base raised to the given power.
    //
    //
    Dword __fastcall PowerOf(Dword dwBase, Dword dwExponent)
    **
    	__asm
    	**
    		/**
    		 *
    		 * ECX - Base.
    		 * EBX - Exponent.
    		 * EAX - Power of the base to the exponent.
    		 *
    		 **/
    
    		// Since MUL uses EDX, we must use EBX for the exponent instead.
    		mov ebx, edx
    
    		// Initialize the raised power to 1.
    		mov eax, 1
    
    		// Raise the base to the exponent.
    		REITERATE:
    			// Check if we've finished.
    			cmp ebx, 0
    			jz BREAK
    
    			// Raise the base by 1.
    			mul ecx
    
    			// Remember how many times we've raised the base.
    			dec ebx
    			jmp REITERATE
    		BREAK:
    		EXIT:
    	}
    }
    
    
    
    ////////////////////////////////////////////////////////////////////////////
    //
    // Memory Functions
    //
    ////////////////////////////////////////////////////////////////////////////
    
    //--------------------------------------------------------------------------
    // Word Endian16(Word)
    // ===================
    //
    // Description:
    //   Reverses the byte-order of a 16-bit value.
    //
    //
    // Parameters:
    //   [Word] [w] - The value of whose byte-order is to be reversed.
    //
    //
    // Return Value:
    //   Returns the given 16-bit value in the oppisite byte-order.
    //
    //
    Word __fastcall Endian16(const Word w)
    **
    	__asm
    	**
    		// Reverse the endian (byte order) of the given 16-bit value.
    		rol cx, 8
    
    		// Return the converted value.
    		mov ax, cx
    	}
    }
    
    ---------------------------------------------------------------------------------------------------------------------------
    
    //--------------------------------------------------------------------------
    // Dword Endian16(Dword)
    // =====================
    //
    // Description:
    //   Reverses the byte-order of a 32-bit value.
    //
    //
    // Parameters:
    //   [Dword] [dw] - The value of whose byte-order is to be reversed.
    //
    //
    // Return Value:
    //   Returns the given 32-bit value in the oppisite byte-order.
    //
    //
    Dword __fastcall Endian32(const Dword dw)
    **
    	__asm
    	**
    		// Reverse the endian (byte order) of the given 32-bit value.
    		rol ecx, 16
    
    		// Return the converted value.
    		mov eax, ecx
    	}
    }
    	
    
    
    ////////////////////////////////////////////////////////////////////////////
    //
    // String & Character Functions
    //
    ////////////////////////////////////////////////////////////////////////////
    
    //--------------------------------------------------------------------------
    // Dword GetStringLength(Char*)
    // ============================
    //
    // Description:
    //   Retrieves the length of an ASCII null-terminated string of characters.
    //
    //
    // Parameters:
    //   [Char*] [pstr] - The string to retrieve the length of.
    //
    //
    // Return Value:
    //   Returns the length of the given string.
    //
    //
    Dword __fastcall GetStringLength(const Char* pstr)
    **
    	__asm
    	**
    		/**
    		 *
    		 * EAX - Maintains a count of the length of the string.
    		 * ECX - Points to the current string element.
    		 *
             **/
    
    		// Initialize the length count to zero.
    		mov eax, 0
    
    		// Count the number of non-null elements of the string.
    		REITERATE:
    			// If the end of the string hasn't been reached, move on to the next
    		    // element, and increment the count accordingly.
    			cmp [ecx], 0
    			jz BREAK
    			inc eax
    			inc ecx
    			jmp REITERATE
    		BREAK:
    	}
    }
    
    
    
    //--------------------------------------------------------------------------
    // Dword IsAlpha(Char)
    // ===================
    //
    // Description:
    //   Determines whether or not a character is part of the alphabet.
    //
    //
    // Parameters:
    //   [Char] [c] - The character being queried.
    //
    //
    // Return Value:
    //   (2) The character is part of the alphabet, and is lower-case.
    //   (1) The character is part of the alphabet, and is upper-case.
    //   (0) The character is not part of the alphabet.
    //
    //
    Dword __fastcall IsAlpha(const Char c)
    **
    	__asm
    	**
    		/**
    		 *
    		 * ECX - The character being queried.
    		 *
    		 **/
    
    		// The query is not alpha until proven otherwise.
    		mov eax, 0
    
    		// Check if the query is below the range of possible alpha characters.
    		cmp cl, 65
    		jb EXIT
    
    		// Check if the query is a upper-case alpha character.
    		cmp cl, 90
    		jbe IS_ALPHA_UPPER
    
    		// Check if the query is above the range of possible alpha characters.
    		cmp cl, 122
    		ja EXIT
    
    		// Check if the query is a lower-case alpha character.
    		cmp cl, 97
    		jae IS_ALPHA_LOWER
    
    		// The query is not in the range of A-Z or a-z, therefor it's not an
    		// alpha character.
    		jmp EXIT
    
    		IS_ALPHA_UPPER:
    		mov eax, 1
    		jmp EXIT
    
    		IS_ALPHA_LOWER:
    		mov eax, 2
    
    		EXIT:
    	}
    }
    
    
    
    //--------------------------------------------------------------------------
    // Dword CompareString(Char*, Char*)
    // =================================
    //
    // Description:
    //   Compares two ASCII null-terminated strings against one-another.
    //
    //
    // Parameters:
    //   [Char*] [pstrLeft]  - First string for comparison.
    //   [Char*] [pstrRight] - Second string for comparison.
    //
    //
    // Return Value:
    //   If the strings match, a non-zero value is returned. Elsewise, if the strings
    //   don't match zero is returned.
    //
    //
    //
    Bool __fastcall CompareString(const Char* pstrLeft, const Char* pstrRight)
    **
    	__asm
    	**
    		/**
    		 *
    		 * ECX - Points to the current element of the left-hand string being compared.
    		 * EDX - Points to the current element of the right-hand string being compared.
    		 *
    		 **/
    
    		/**
    		 *
    		 * If the string's aren't of the same length, then they certainly don't match.
    		 *
    		 **/
    		
    		// Retrieve the length of both the left and right strings, the results
    		// being stored in EAX and EBX.
    		mov esi, ecx
    		call GetStringLength
    		mov ebx, eax
    		mov ecx, edx
    		call GetStringLength
    
    		// Compare the length of the two strings, if they don't match then we
    		// can claim they don't match.
    		cmp ebx, eax
    		jnz EXIT_NO_MATCH
    
    		// Compare the corrosponding elements of each string against one-another.
    		REITERATE:
    			// Check if we've reached the end of the strings. This would indicate
    			// the strings match.
    			cmp [edx], 0
    			jnz CONTINUE
    			// The strings match.
    			mov eax, 1
    			jmp EXIT_MATCH
    
    			CONTINUE:
    			// Compare the elements, and if they don't match then obviously the
    			// strings are _not_ equal.
    			mov bl, [esi]
    			cmp bl, [edx]
    			jnz EXIT_NO_MATCH
    
    			// Move on to the next element of each string.
    			inc edx
    			inc esi
    
    			jmp REITERATE
    		BREAK:
    		EXIT_NO_MATCH:
    		// The strings don't match.
    		mov eax, 0
    		
    		EXIT_MATCH:	
    	}
    }
    
    
    
    //--------------------------------------------------------------------------
    // Dword CompareStringNoCase(Char*, Char*)
    // =======================================
    //
    // Description:
    //   Compares two ASCII null-terminated strings against one-another, ignoring
    //   the case of alpha characters.
    //
    //
    // Parameters:
    //   [Char*] [pstrLeft]  - First string for comparison.
    //   [Char*] [pstrRight] - Second string for comparison.
    //
    //
    // Return Value:
    //   If the strings match, a non-zero value is returned. Elsewise, if the strings
    //   don't match zero is returned.
    //
    //
    //
    Bool __fastcall CompareStringNoCase(const Char* pstrLeft, const Char* pstrRight)
    **
    	__asm
    	**
    		/**
    		 *
    		 * ECX - Points to the current element of the left-hand string being compared.
    		 * EDX - Points to the current element of the right-hand string being compared.
    		 *
    		 **/
    
    		/**
    		 *
    		 * If the string's aren't of the same length, then they certainly don't match.
    		 *
    		 **/
    		
    		// Retrieve the length of both the left and right strings, the results
    		// being stored in EAX and EBX.
    		mov esi, ecx
    		call GetStringLength
    		mov ebx, eax
    		mov ecx, edx
    		call GetStringLength
    
    		// Compare the length of the two strings, if they don't match then we
    		// can claim they don't match.
    		cmp ebx, eax
    		jnz EXIT_NO_MATCH
    
    		// Compare the corrosponding elements of each string against one-another,
    		// ignoring their possible case differences.
    		REITERATE:
    			// Check if we've reached the end of the strings. This would indicate
    			// the strings match.
    			cmp [edx], 0
    			jnz CONTINUE
    			// The strings match.
    			mov eax, 1
    			jmp EXIT_MATCH
    
    			CONTINUE:
    			// Compare the elements, and if they don't match then obviously the
    			// strings are _not_ equal.
    			mov bl, [esi]
    
    			COMPARE:
    			cmp bl, [edx]
    			jz CONTINUE2
    
    			// See if we're able to switch the case of one of the characters.
    			mov cl, bl
    			call IsAlpha
    			cmp eax, 0
    			jz EXIT_NO_MATCH
    
    			// If the character is upper-case, switch it to lower-case.
    			cmp eax, 1
    			jnz NOT_UPPER
    			add bl, 32
    			jmp COMPARE_CASE_SWITCH
    
    			NOT_UPPER:
    			sub bl, 32
    
    			COMPARE_CASE_SWITCH:
    			// Compare the characters again, after the case-switch.
    			cmp bl, [edx]
    			jnz EXIT_NO_MATCH
    
    			CONTINUE2:
    			// Move on to the next element of each string.
    			inc edx
    			inc esi
    
    			jmp REITERATE
    		BREAK:
    		EXIT_NO_MATCH:
    		// The strings don't match.
    		mov eax, 0
    		
    		EXIT_MATCH:	
    	}
    }
    
    
    
    //--------------------------------------------------------------------------
    // Byte CharToInt(Char)
    // ====================
    //
    // Description:
    //   Converts an ASCII character representing an integer, to an actualy integer
    //   in it's binary form.
    //
    //
    // Parameters:
    //   [Char] [c] - The character being converted.
    //
    //
    // Return Value:
    //   Returns the binary form of the digit being represented by the given character.
    //
    //
    Byte __fastcall CharToInt(const Char c)
    **
    	__asm
    	**
    		/**
    		 *
    		 * CL - The character being converted to binary.
    		 *
    		 **/
    
    		// We'll use EAX now.
    		movzx eax, cl
    
    		// Ensure the character is not below the minimum range of decimal digits.
    		cmp al, 48
    		jb EXIT
    
    		// Check if the character is not part of the decimal system.
    		cmp al, 57
    		ja HEX
    		// The character is a decimal digit. Convert it.
    		sub al, 48
    		jmp EXIT
    
    		HEX:
    		// The character is a hexadecimal digit. Convert it.
    		sub al, 55
    
    		EXIT:
    	}
    }
    
    
    
    Char __fastcall IntToChar(const Byte i)
    **
    	__asm
    	**
    		/**
    		 *
    		 * CL - The integer value being converted.
    		 *
    		 **/
    
    		// We'll use EAX now.
    		movzx eax, cl
    
    		// Check if the integer represents a hexadecimal digit. 
    		cmp al, 9
    		ja HEX
    		// The integer is in the decimal range (0-9), convert it.
    		add al, 48
    		jmp EXIT
    
    		HEX:
    		// The integer is in the hexadecimal range (A-F), convert it.
    		add al, 55
    
    		EXIT:
    	}
    }
    
    
    
    //--------------------------------------------------------------------------
    // Dword StrToInt(Char*, Dword)
    // ============================
    //
    // Description:
    //   Converts a string of characters representing an integer to an actual
    //   binary integer.
    //
    //
    // Parameters:
    //   [Char*] [pstr]   - The string to be converted.
    //   [Dword] [dwBase] - The base number system the given string is in.
    //
    // Return Value:
    //   Returns the binary form of the given string.
    //
    //
    // Remarks:
    //   The 'dwBase' parameters must be greater than 1. If it isn't, StrToInt()'s
    //   behaviour is undefined.
    //
    //
    Dword __fastcall StrToInt(const Char* pstr, Dword dwBase)
    **
    	Dword dwResult = 0;
    
    
    	__asm
    	**
    		/**
    		 *
    		 * ESI - Current digit position being processed.
    		 * EDI - Points to the current character being processed.
    		 * EBX - Base system being used.
    		 *
    		 **/
    
    		// Swap parameters into different registers so we can interface with
    		// other routines properely.
    		mov edi, ecx
    		mov ebx, edx
    
    		// Retrieve the length of the string, so we know the greatest positional
    		// value it's using.
    		call GetStringLength
    		mov esi, eax
    
    		// Check if the string is empty, in which case the result is always going
    		// to be zero.
    		cmp esi, 0
    		jz EXIT
    		dec esi
    		
    		// Convert the string into the integer it's representing.
    		REITERATE:
    			// Check if we've reached the end of the string.
    			cmp esi, 0xFFFFFFFF
    			jz BREAK
    
    			// Calculate the positional value of the current digit.
    			mov ecx, ebx // 'dwBase'
    			mov edx, esi // 'dwExponent'
    			call PowerOf
    			mov edx, eax
    
    			// Convert the current character to it's proper integer form.
    			mov cl, [edi]
    			call CharToInt
    
    			// Calculate the position's contribution.
    			mov ecx, edx
    			mul ecx
    
    			// Add the positions contribution to the final result.
    			add [dwResult], eax
    
    			// Move through the string.
    			dec esi
    			inc edi
    
    			jmp REITERATE
    		BREAK:
    
    		EXIT:
    		// Return the proper value.
    		mov eax, [dwResult]
    	}
    }
    
    
    
    //--------------------------------------------------------------------------
    // Void IntToStr(Dword, Dword, Char*)
    // ==================================
    //
    // Description:
    //   Converts an integer into a string of characters appropiately representing
    //   it.
    //
    //
    // Parameters:
    //   [Dword] [dw]         - The integer value being converted.
    //   [Dword] [dwBase]     - The base system the output string should be in.
    //   [Char*] [pstrOutput] - Pointer to a buffer which will receive the resulting string.
    //
    // Return Value:
    //   Returns the binary form of the given string.
    //
    //
    // Remarks:
    //   None.
    //
    //
    Void __fastcall IntToStr(Dword dw, Dword dwBase, Char* pstrOutput)
    **
    	__asm
    	**
    		/**
    		 *
    		 * ESI - Index of the current digit being processed.
    		 * EDI - Base system.
    		 * EBX - The integer value.
    		 *
    		 **/
    
    		// Check if the integer is zero, so we can exit quick.
    		cmp ecx, 0
    		jnz CONTINUE
    
    		// Zero is always zero.
    		mov ebx, pstrOutput
    		mov [ebx], 48 // '0'
    		jmp EXIT
    
    		CONTINUE:
    		// Prepare alternate parameter storage.
    		mov ebx, ecx
    		mov edi, edx
    
    		// Begin at the smallest digit index.
    		mov esi, 0
    
    		// Retrieve the greatest positional value being used by the integer.
    		REITERATE:
    			// Calculate the current positional value.
    			mov ecx, edi
    			mov edx, esi
    			call PowerOf
    
    			// Put the positional value on the stack for later use, so we
    			// don't have to re-calculate it.
    			push eax
    
    			// Check if we've reached a positional value which exceeds our
    			// 32-bit boundaries. Which means no matter what, we've reached
    			// a positional value not needed by the integer.
    			cmp edx, 0
    			jnz BREAK
    
    			// Check if we've found a positional value that is not needed
    			// by the integer.
    			cmp eax, ebx
    			ja BREAK
    
    			// Move on to the next digit index, and thus positional value.
    			inc esi
    
    			jmp REITERATE
    		BREAK:
    
    		// Remove the unused positional value from the stack.
    		pop eax
    
    		// This will prevent integer-overflows.
    		mov edx, 0
    
    		// Generate the string representation of the integer.
    		REITERATE2:
    			// Check if we've finished converting the whole integer.
    			cmp esi, 0
    			jz BREAK2
    
    			// Retrieve the next positional value being processed.
    			pop ecx
    
    			// Calculate the number of times the positional value is being
    			// used. Hence, the digit which would be residing under it in
    			// the number.
    			mov eax, ebx
    			div ecx
    			mov edi, eax
    
    			// Calculate the contribution of this positional value, and remove
    			// it from the integer.
    			mul ecx
    			sub ebx, eax
    
    			// Convert the digit into it's character form.
    			mov ecx, edi
    			call IntToChar
    
    			// Copy the character into the output string.
    			mov ecx, pstrOutput
    			mov [ecx], al
    
    
    			// Move on to the next positional value, and the next element in the
    			// output string.
    			dec esi
    			inc [pstrOutput]
    
    			jmp REITERATE2
    		BREAK2:
    
    		EXIT:
    	}
    }
    Utility.h


    Code:
    /*
     * Utility.h
     * =========
     * Copyright (C) Matthew J. W.
     * All rights reserved.
     * Version 1.0
     *
     *
     * Description:
     *   Interface to the Utility module.
     *
     *
     *******************************************************************************************************************************************************/
    #pragma once
    
    
    
    //--------------------------------------------------------------------------
    // Functions
    //--------------------------------------------------------------------------
    extern Dword __fastcall PowerOf(Dword dwBase, Dword dwExponent);
    extern Word __fastcall  Endian16(const Word w);
    extern Dword __fastcall Endian32(const Dword dw);
    extern Dword __fastcall GetStringLength(const Char* pstr);
    extern Dword __fastcall IsAlpha(const Char c);
    extern Bool __fastcall  CompareString(const Char* pstrLeft, const Char* pstrRight);
    extern Bool __fastcall  CompareStringNoCase(const Char* pstrLeft, const Char* pstrRight);
    extern Byte __fastcall  CharToInt(const Char c);
    extern Char __fastcall  IntToChar(const Byte i);
    extern Dword __fastcall StrToInt(const Char* pstr, Dword dwBase);
    extern Void __fastcall  IntToStr(Dword dw, Dword dwBase, Char* pstrOutput);
    Last edited by KarLi; 02-06-09 at 09:58 AM.


  2. #2
    Gamma Daevius is offline
    MemberRank
    Jun 2007 Join Date
    NetherlandsLocation
    3,252Posts

    Re: [C++] Example codes

    Changed topic title, use a more descriptive title next time (using language tags!).

    Also, your opening brackets are wrong, they look replaced by **.

  3. #3

    Re: [C++] Example codes

    Sorry sorry
    and ty



Advertisement