![]() |
![]() |
![]() |
|||||
![]() |
![]() |
![]() |
![]() |
![]() |
|||
| Welcome
to Tech Support Forum home to more then 136,000 problems solved. Issues
have included: Spyware, Malware, Virus Issues, Windows, Microsoft,
Linux, Networking, Security, Hardware, and Gaming Getting your
problem solved is as easy as: 1. Registering for a free account 2. Asking your question 3. Receiving an answer Registered members: * See fewer ads. * And much more..
|
| Want to know how to post a question? click here | Having problems with spyware and pop-ups? First Steps |
|
|||||||
| Programming A discussion forum for programs and programming used in tech-related businesses. |
![]() |
|
|
LinkBack | Thread Tools |
|
|
#1 (permalink) |
|
Be Free
|
Code...
Here's A Place To Post Your Code. I Would Like To See Some Of The Creative Things You Can Come Up With Through Your Programming. But Hold On, We Need A Format... Ok, So
<language> <special programs to run it> <purpose/reason> <code> //please use the [code] tags to make it nead! Now Let's Get Out there And Program!
__________________
Suicide Command in Linux : rm -rf / ;) AIM:TheLoneWolf071@aim.com--If You Need Help, Don't Hesitate... |
|
|
|
| Important Information |
|
Join the #1 Tech Support Forum Today - It's Totally Free!
TechSupportForum.com is a leading support website for your computer needs. We offer free, friendly and personalized computer support. Why pay to have your computer fixed when you can do it for free. Join TechSupportforum.com Today - Click Here |
|
|
#3 (permalink) |
|
Be Free
|
Code:
/*
Created By DarkRedRose( @)--}--- )
Created On November 05, 2005
Created For:Searching Documents, Just Enter The Document Name And
This Will Locate It And Tell You Where.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <unistd.h> //use if in linux
#include <math.h>
#define s_buffer 80
char *flush(char *);
/*
fgets leaves a pesky \n at the end of ever string to know when it's finished
so we make a function to get rid of it, hence the flush
*/
int main(int argc, char *argv[])
{
char
string_to_lookfor[s_buffer],
string_searching[s_buffer],
filename[s_buffer],
temp_string[s_buffer];
long unsigned int
search_number=0,
for_i,
for_j, //special variables for the for loop
for_k;
FILE *search_file;
printf("What File Would You Like To Search?\n:"); //Asks Filename
fgets(filename, s_buffer, stdin); //Takes filename
if(strlen(filename) == 0 || strcmp(filename, "\n") == 0)
{
printf("Woops! You Forgot To Enter A Value, Quiting Now!\n");
exit(0);
}
strcpy(filename, flush(filename));
search_file = fopen(filename, "r"); //opens the filename and assigns the stream to the searchfile pointer
if(search_file == NULL)
{
perror(search_file);
/*
prints reason error, compiler will give you flack about it not
being a pointer, don't worry about that
*/
exit(0); //quits if it doesn't exist
}
printf("\nWhat String Would You Like To Search For?\n:");
fgets(string_to_lookfor, s_buffer, stdin);
if(strlen(string_to_lookfor) == 0 || strcmp(string_to_lookfor, "\n") == 0)
{
printf("Woops! You Forgot To Enter A Value, Quiting Now!\n");
exit(0);
}
strcpy(string_to_lookfor, flush(string_to_lookfor)); //takes off the end \n
search_number = strlen(string_to_lookfor); //number of char's in the string
for(for_i=0; !feof(search_file); for_i++)
{
fgets(string_searching, s_buffer, search_file);
if(strlen(string_searching) == 0 || strcmp(string_searching, "\n") == 0)
{
continue;
}
strcpy(string_searching, flush(string_searching));
for(for_j = 0; for_j < strlen(string_searching); for_j++)
{
for(for_k = 0; for_k < search_number; for_k++)
{
temp_string[for_k] = string_searching[for_k+for_j];
}
temp_string[for_k] = '\0';
/*
Ok, So temp_string likes to tag on ugly letters at the end,
so we need this go get rid of it
*/
if((strcmp(string_to_lookfor, temp_string)) == 0)
{
printf("Match Found For %s! It's On Line:%lu At Character:%lu\n",string_to_lookfor, for_i+1, for_j+1);
}
}
}
fclose(search_file);
return 0;
}
char *flush(char *string_flush)
{
if(string_flush[strlen(string_flush) - 1] == '\n')
{
string_flush[strlen(string_flush) - 1] = '\0'; //last char will be \0
}
return string_flush;
}
|
|
|
|
|
|
#4 (permalink) |
|
Registered User
|
I liked your idea and heres what I came up with for it:
Usage: Code:
tgo@localhost:~/c$ cat test askdfkl asdfasdf BOB dsf BOB JOE TIM BOB tgo@localhost:~/c$ gcc -o search search.c tgo@localhost:~/c$ ./search Usage: search <file> <text> tgo@localhost:~/c$ ./search test BOB Match found at line: 3 Match found at line: 5 Match found at line: 8 tgo@localhost:~/c$ Code:
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{
FILE *file;
char cur[80];
int x;
x = 1;
if (argc != 3)
{
printf("Usage: search <file> <text>\n");
exit(1);
}
if ((file = fopen(argv[1],"r")) == NULL)
{
printf("Error opening file.\n");
exit(1);
}
while (fgets(cur, 80, file))
{
if(strstr(cur,argv[2]))
{
printf("Match found at line: %d\n",x);
}
x++;
}
return 0;
}
__________________
My new homepage: |
|
|
|
|
|
#5 (permalink) |
|
Be Free
|
Very Nice... Here's A New One, It's Short And Sweet, But Find The Factors Of any number, upto 2^32...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
unsigned long int
for_i,
for_j,
factor_input;
if(argc!=2)
{
printf("Usage: %s <Number To Factor>\n", argv[0]);
exit(0);
}
for(for_j=0; for_j < strlen(argv[1]); for_j++)
{
if(isdigit(argv[1][for_j]) == 0)
{
printf("You Must Enter A Number!\n");
exit(0);
}
}
factor_input=atoi(argv[1]);
if(factor_input > 2147483647)
{
printf("AHHHH, Number's To Big\n");
exit(0);
}
printf("The Factors of %lu Are :\n\n", factor_input);
for(for_i = 1; for_i < factor_input+1; for_i++)
{
if(factor_input%for_i == 0)
{
printf("%lu\n", for_i);
}
}
printf("\n");
return 0;
}
__________________
Suicide Command in Linux : rm -rf / ;) AIM:TheLoneWolf071@aim.com--If You Need Help, Don't Hesitate... |
|
|
|
|
|
#7 (permalink) |
|
TSF Enthusiast
Join Date: Dec 2004
Posts: 604
OS: windows xp
|
//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;
}
__________________
|
|
|
|
|
|
#9 (permalink) | |
|
TSF Enthusiast
Join Date: Dec 2004
Posts: 604
OS: windows xp
|
Quote:
__________________
|
|
|
|
|
|
|
#10 (permalink) |
|
Registered User
|
Here is some linux assembly that takes in two numbers and gives you the output. Not very cool but was playing with C functions in assembly.
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
__________________
My new homepage: |
|
|
|
|
|
#11 (permalink) |
|
Registered User
|
I was in some random irc channel and they had a bot spit out the latest forum threads so I decided to code my own and then after it was done I thought it would be cool to make one for active forum users and here is the code.
Usage: Code:
<tgo> !users <Forums> Currently Logged in Users: john, Niels, tgo <tgo> !forum <Forums> Latest Forum Post: Forums irc bot -> http://www.anomalous-security.org/forum/viewtopic.php?t=1261 Code:
#!/usr/bin/perl -w
# Bot that reads the last forum post coded by Niels and tgo
# http://www.anomalous-security.org
use IO::Socket;
$server = "snake.zq1.de";
$nick = "Forums";
$ircport = 6667;
$httpport = 80;
$channel = "#aso";
Start();
sub Start {
$CONNECTION = IO::Socket::INET->new (
PeerAddr => $server,
PeerPort => $ircport,
Proto => 'tcp'
) or die;
print $CONNECTION "USER $nick 0 0 :$nick\n";
print $CONNECTION "NICK $nick\n";
print $CONNECTION "JOIN $channel\n";
while (my $input = <$CONNECTION>) {
if ($input =~ /:tgo!tgo\@je.to.jne/)
{
if ($input =~ /:!forum/)
{
getpage("/","rss_feeds2");
lastpost();
}
elsif ($input =~ /:!users/)
{
getpage("/forum/index.php","Registered Users:");
getuser();
}
}
print $CONNECTION "PONG $1\n" if $input =~ /PING (.*)/;
}
}
sub getpage {
my ($page,$keyword) = @_;
print "page is $page\n";
print "keyword is $keyword\n";
$CON = IO::Socket::INET->new (
PeerAddr => $server,
PeerPort => $httpport,
Proto => 'tcp'
) or die;
$request = "GET $page HTTP/1.1\r\n";
$request .= "Host: www.anomalous-security.org\r\n";
$request .= "User-Agent: Forums Bot\r\n";
$request .= "Connection: close\r\n\r\n";
print $CON $request;
while (my $text = <$CON>)
{
$all .= $text;
if ($text =~ /$keyword/)
{
$spot = length($all);
$s = $spot - length($text);
}
if ($text =~ /This data is based/)
{
$end = ($s - length($all)) * -1;
}
}
}
sub lastpost {
$chunk = substr($all,$spot+94,100);
$chunk =~ /(.*)">(.*)<\/a\>/;
print $CONNECTION "PRIVMSG $channel :Latest Forum Post: $2 -> http://www.anomalous-security.org/$1\n";
close($CON);
}
sub getuser {
$chunk = substr($all,$s,$end);
if ($chunk =~ /Registered Users: None/)
{
$names = "None";
}
else
{
$chunk =~ s/<([^>]*)>//g;
$chunk =~ /Registered Users: (.*)\s+/;
$names = $1;
}
print $CONNECTION "PRIVMSG $channel :Currently Logged in Users: $names\n";
}
__________________
My new homepage: |
|
|
|
|
|
#12 (permalink) |
|
Registered User
|
Code to break Caesars Box encrpytion.
Useage: Code:
tgo@localhost:~/perl$ perl cryp.pl HOUIY\!TO\! HITOYOU!! tgo@localhost:~/perl$ perl cryp.pl hoacfucdoowkach\?wdocwku?mwohoccluoduookacuccduwwhlhkclolwduihdo\! howmuchwoodwouldawoodchuckchuckifawoodchuckcouldchuckwood??lawl! tgo@localhost:~/perl$ 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: 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);
}
}
for ($y=0;$y<$num;$y++)
{
for($in=0;$in<$length-$num;$in++)
{
$spot = $in*$num+$y;
if ($spot > $length)
{
last;
}
if ($in == 0)
{
$curline = substr($string,$spot,1);
}
else
{
$curline .= substr($string,$spot,1);
}
}
print $curline;
}
print "\n";
__________________
My new homepage: |
|
|
|
|
|
#13 (permalink) |
|
Be Free
|
Just For All Of You... Post you Code On redrose.homelinux.com via SSH Or FTP. If You Use FTP, login is
User:ftp Pass:<blank> -- FTP will not work with your browser... SSH is User:anon1 pass:anonymous if you use ssh, compile you code please... if FTP, i'll move your code to anon1 and compile it for you... P.S., also Post your Code Here...
__________________
Suicide Command in Linux : rm -rf / ;) AIM:TheLoneWolf071@aim.com--If You Need Help, Don't Hesitate... |
|
|
|
|
|
#14 (permalink) |
|
Be Free
|
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;
}
__________________
Suicide Command in Linux : rm -rf / ;) AIM:TheLoneWolf071@aim.com--If You Need Help, Don't Hesitate... |
|
|
|
|
|
#15 (permalink) |
|
Analyst, Security Team
Join Date: Nov 2005
Location: UK
Posts: 1,968
OS: xp
|
// Delphi
// selects 6 random numbers 1-49 LotteryNumbers.jpg 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;
|
|
|
|
|
|
#16 (permalink) |
|
Registered User
Join Date: Dec 2005
Posts: 5
OS: XP
|
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;
}
For Dev-C++ link to: libWS2_32.a Last edited by Cache; 02-16-2006 at 05:46 AM. |
|
|
|
|
|
#17 (permalink) |
|
Registered User
Join Date: Aug 2005
Posts: 8
OS: XP
|
Can any of you programmers help me? i want to get something to add to a video clip to automatically delete it after its been watched once.
Kind of like a secret agent thing. I would be very greatful if you could help me out or tell me where i can download such a thing... |
|
|
|
|
|
#18 (permalink) | |
|
Registered User
Join Date: Jul 2006
Posts: 4
OS: WinXP
|
Quote:
|
|
|
|
|
|
|
#19 (permalink) |
|
Analyst, Security Team
Join Date: Nov 2005
Location: UK
Posts: 1,968
OS: xp
|
Hi suckonthat
calling on rand or random will by default produce the same random numbers each time the program is started. However to produce different sets of random numbers each run then you have to call on a seed ie srand or srandom. Set the seed to the system clock as in mgoldb2's code like so srand(time(0)) calls the random number and multiplies it with the system time. This gives you greater scope for randomness as the time will be different each run. You can set the seed to timeofday or uclock if you need to produce more than 1 random number per second. |
|
|
|
|
|
#20 (permalink) |
|
Registered User
|
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:
/*
* 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:
}
}
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); -Matt |
|
|
|
![]() |
| Thread Tools | |
|
|