Thursday, July 31, 2008

C Code for Heapsort algorithm

heapsort(x,n)

int x[],n;

{

int i,data,s,f,ivalue;

/* create initial heap */

for(i=1;i <>

{

data=x[i];

/* insert_heap (x,i,data); */

s=i;

f=(s - 1) / 2; /* f is the father of s */

while(s > 0 && x[f] <>

{

x[s]=x[f]; /* move up the tree */

s=f;

f=(s - 1) / 2; /* f is the father of s */

}/* end while */

x[s]=data;

}/* end for i.e. a heap has been created */

/* begin repeatedly removing the maximum element i.e. x[0], */

/* place it at the end of the array.*/

/* Convert the remaining part to a heap */

for(i=n - 1; i > 0;i--)

{

/* delete the root */

ivalue=x[i];

x[i]=x[0]; /* the root is placed at the bottom */

f=0;

/* begin adjusting the heap by pushing the element x[i] i.e. ivalue */

if(i == 1)

s=-1;/* no further processing required */

else

s=1;

if(i > 2 && x[2] > x[1])

s=2;

while(s >=0 && ivalue <>

{

/* push ivalue down the heap */

x[f]=x[s];

f=s;

/* s=largeson(f, i-1) */

s=2*f +1; /* s is the child of f */

if(s+1 <= i-1 && x[s] <>

s=s+1; /* select the larger of the two children of f i.e. 2j + 1 or 2j + 2 */

if(s > i-1) /* when bounds have been reached */

s=-1;

}/* end while */

/* insert ivalue at fth location */

x[f]=ivalue;

}/* end for */

}/* end heap sort */

C code for NONRECURSIVE IMPLEMENTATION OF QUICKSORT

# define STACKSIZE 50

void quicksort(int x[], int n)

{

int i,j;

struct stack_info{

int l;

int u;

}bounds;

struct stack_tag{

int stacktop;

struct stack_info limits[STACKSIZE];

}STACK;

STACK.stacktop=-1;

bounds.l=0;

bounds.u=n - 1;

push(&STACK,&bounds);

while(!empty(&STACK))

{

pop(&STACK,&bounds);

while(bounds.u > bounds.l)

{

partition(x,bounds.l,bounds.u,&j);

if((j - bounds.l) > (bounds.u - j))

{

i=bounds.u;

bounds.u=j - 1;

push(&STACK,&bounds);

bounds.l=j + 1;

bounds.u=i;

}

else

{

i=bounds.l;

bounds.l=j + 1;

push(&STACK,&bounds);

bounds.l=i;

bounds.u=j - 1;

} /* end if */

} /* end while */

}/* end while */

return;

} /* end quicksort */

int emtpy (struct stack_tag * stackptr)

{

if( stackptr->stack.top == -1)

return (1);

else

return (0);

} /* end empty*

void pop (struct stack_tag * stackptr, struct stack_info * data)

{

if empty (stackptr)

{

printf (“%s\n”, “stack underflow”);

}

data=&(stackptr-> limits [stackptr->stacktop]);

-- (stackptr->stacktop);

return;

}

void push (struct stack_tag * stackptr, struct stack_info *data)

{

int p;

p=++(stackptr->stacktop);

stackptr->limits[p].l = data->l;

stackptr->limits [p].u = data->u;

return;

} /*end push.; note no checking for stack overflow */

C code for A recursive implementation of the quicksort algorithm.


void quicksort(int x[], int l, int u)

{

int * j; int k;

if (l > =u)

return;

else

{

partition (x, l,u,&j);

quicksort (x, l, j -1);

quicksort (x, j+1, u);

return;

}

}

void partition (int x [], int l, int u,int *j)

{

int k, m,n, i, temp, int * j;

k = x [l]; /* k is the element whose final */

n = u; /* position is required */

m =l;

while (m <>

{

while (x[m] <= k && m <>

m++ ; /* move the lower index up */

while (x[n] > k)

n --; /* reduce the upper index */

if (m

{

/*interchange x[m] & x[n] */

temp=x[m];

x[m]=x[n];

x[n]=temp;

} /* end if */

} * end while */

x[l]= x[n];

x[n]=k;

* j = n;

return;

}

Wednesday, July 30, 2008

C++ Source code for using STL unary_functions.

#include "stdafx.h"

#include
#include
#include
#include // for remove_if
#include
#include
using namespace std;

template
class is_vowel : public unary_function {

public:
bool operator ()(T t) const
{
if ((t=='a')||(t=='e')||(t=='i')||(t=='o')||(t=='u'))
return true; //t is a vowel
return false; // t is not a vowel
}
};

bool greaterthan(int x) {

return x>6;
}
int main()
{

string original;
cout << "Type string to remove vowels." <<>> original;
//…

string::iterator it= remove_if(original.begin(),
original.end(),
is_vowel());

// create new string from original using previous iterator
string no_vowels(original.begin(),it);
cout <<<><< "Remove all numbers greater than 6" < v1;
v1.push_back(7);
v1.push_back(1);
v1.push_back(9);
v1.push_back(2);
v1.push_back(0);
v1.push_back(7);
v1.push_back(7);
v1.push_back(3);
v1.push_back(4);
v1.push_back(6);
v1.push_back(8);
v1.push_back(5);
v1.push_back(7);
v1.push_back(7);

for(vector::iterator itr_prn = v1.begin() ;itr_prn!= v1.end(); itr_prn++)
cout<<" "<< *itr_prn ; cout <::iterator itre = remove_if(v1.begin(),v1.end(),greaterthan);
vector::iterator itrb = v1.begin();

for(;itrb != itre; itrb++)
cout << " " << *itrb;


}

C Source code for reversing a singly linked list.

void reverse(node **head) {

node *current = *head;
node *result = 0;
node *next;
while (current != 0) {

next = current->next;
current->next = result;
result = current;

current = next;
}
*head = result;
}

C Source code for checking if a number is power of 2

void root( int & nn) {
nn = nn/2;
}

int PowerOf2() {

int n ;
char ch='q';

do {

printf("\nEnter No: ");
scanf("%d",&n);
if((n & n-1) == 0) {

int temp =n;
while(temp >0 && temp%2 ==0 ) {

printf(" %d *", temp);
root(temp);
}
}
else {

printf("\n No is not a power of 2.");
}
printf("\nDo you want to continue.... :");
scanf("%c", &ch);
}while(ch!='q');

return 0;
}

Monday, July 28, 2008

C source code for converting an integer to binary.

char *int2bin(int a)
{
char *str,*tmp;
int cnt = 31;
str = (char *) malloc(33); /*32 + 1 , becoz its a 32 bit bin number*/
tmp = str;
while ( cnt > -1 ){
str[cnt]= '0';
cnt --;
}
cnt = 31; printf("\n");
while (a > 0){

if (a%2==1){
str[cnt] = '1';
printf(" 1");
}
else
printf(" 0");
cnt--;
a = a/2 ;
}
return tmp;

}

C Macro for verifying MSB

#define zero_most_significant(h) \
(h&=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16))

C Macro Source Code for verifying if a number is power of two.

#define power_of_two(x) ((x)&&(~(x&(x-1))))

C Source code for palindrome problem.

struct ppair {
char c;
int first;
int last;
int num_inner_pairs;
ppair ** inner_pairs;
};

void add_to_inner( ppair * outer, ppair * inner) {

ppair ** temp;
int i;

temp = ( ppair * *)malloc((outer->num_inner_pairs + 1) * sizeof( ppair *));
for(i = 0; i <>num_inner_pairs; i++) {
temp[i] = outer->inner_pairs[i];
}
if (outer->num_inner_pairs > 0) {
free(outer->inner_pairs);
}
temp[outer->num_inner_pairs++] = inner;
outer->inner_pairs = temp;
}

void print_palendromes(const ppair * p, char * pre) {
int i;

printf("%s", pre); putc(p->c, stdout);
if (p->first <>last) {
putc(p->c, stdout);
}
for(i = strlen(pre); i > 0; i--) putc(pre[i-1], stdout);
printf("\n");

pre[strlen(pre)] = p->c;
for(i = 0; i <>num_inner_pairs; i++) {
print_palendromes(p->inner_pairs[i], pre);
}
pre[strlen(pre) - 1] = 0;
}

int pallindrome(int argc, const char ** argv) {
int i, j, k;
ppair g, * p;
char * buf;

if (argc != 2) {
fprintf(stderr, "usage: %s string\n", argv[0]);
return -1;
}

g.first = -1;
g.last = strlen(argv[1]);
g.num_inner_pairs = 0;

for(i = 0; i < strlen(argv[1]); i++) {
for(j = i; j < strlen(argv[1]); j++) {
if (argv[1][i] == argv[1][j]) {
ppair * p = ( ppair *)malloc(sizeof( ppair));
p->c = argv[1][i];
p->first = i;
p->last = j;
p->num_inner_pairs = 0;
for(k = 0; k < g.num_inner_pairs; k++) {
if (g.inner_pairs[k]->first <>last) {
add_to_inner(g.inner_pairs[k], p);
}
}
add_to_inner(&g, p);
}
}
}

buf = (char *)malloc(strlen(argv[1]) + 1);
memset(buf, 0, strlen(argv[1]) + 1);

for(k = 0; k < g.num_inner_pairs; k++) {
if (g.inner_pairs[k]->first <>last) {
print_palendromes(g.inner_pairs[k], buf);
}
}

for(k = 0; k < g.num_inner_pairs; k++) {
if (g.inner_pairs[k]->num_inner_pairs > 0) {
free(g.inner_pairs[k]->inner_pairs);
}
free(g.inner_pairs[k]);
}
free(g.inner_pairs);
free(buf);

return 0;
}

C Source code for multiplying two numbers without using multiplication operator.

int multiply( int num, int num1) {

num = (num << 3) - num;
return num;
}

C Source code for counting 1's in a number.

int bitcount (unsigned int n)
{
int count=0;
int counter =0;
while (n)
{
count += n & 0x1u ;
n >>= 1 ;
counter++;
}
return count ;
}

C Source code for converting from Integer to String - itoa implementation.

void IntToStr( int num) {

bool bNegative =false;
if( num < 0)
bNegative =true;
char * str = new char[11];
int i =0;
while( num != 0) {

str[i++] = num % 10 + '0';
num /=10;
}
i--; int j =0;
while( j
char ch = str[j];
str[j] = str[i];
str[i] = ch;
j++; i--;
}

}

C Source Code for reversing a string.

void ReverseString( char str[]) {

int start =0 ;int end = strlen(str)-1;
while(start < end) {

char ch = str[start];
str[start] = str[end];
str[end] = ch;

start++; end--;
}
}

C Source code for Converting from string to integer - atoi implementation

int StrToInt( char str[]) {

bool bFlagNeative =false;
if( str[0] == '-') {

bFlagNeative =true;
}
int i=0;
int num =0;
while(str[i] != '\0') {

num *=10;
num+= (str[i++] - '0');
}
if(bFlagNeative)
num *= -1;
return num;

}

C Source code for reversing words in a string.

bool reverseWords( char str[] ){
char *buffer;
int tokenReadPos, wordReadPos, wordEnd, writePos = 0;

/* Position of the last character is length - 1 */
tokenReadPos = strlen(str) - 1;

buffer = (char *) malloc(tokenReadPos + 2);
if( !buffer )
return false; /* reverseWords failed */

while( tokenReadPos >= 0 ){

if( str[tokenReadPos] == ' ' ){ /* Non-word characters */
/* Write character */
buffer[writePos++] = str[tokenReadPos--];

} else { /* Word characters */
/* Store position of end of word */
wordEnd = tokenReadPos;

/* Scan to next non-word character */
while( tokenReadPos >= 0 && str[tokenReadPos] != ' ' )
tokenReadPos--;

/* tokenReadPos went past the start of the word */
wordReadPos = tokenReadPos + 1;

/* Copy the characters of the word */
while( wordReadPos <= wordEnd ){
buffer[writePos++] = str[wordReadPos++];
}
}
}
/* null terminate buffer and copy over str */
buffer[writePos] = '\0';
strcpy(str, buffer);

free(buffer);

return true; /* ReverseWords successful */
}

Visual Basic Source code for AES Algorithm

Private Const BlkLenMax = 32 ' maximum block length in bytes
Private Const KeyLenMax = 32 ' maximum block length in bytes
Private Const KeySchLenMax = 128 ' maximum key schedule length in bytes
Private BlkLen As Integer ' actual block length
Private KeyLen As Integer ' actual key length

Private Type AESctx ' Type to hold the AES context data
Ekey(0 To KeySchLenMax - 1) As Long
Nrnd As Long
Ncol As Long
End Type

Private Type KeyBlk ' Type to hold user key data
K(0 To KeyLenMax - 1) As Byte
End Type

Private Type IoBlk ' Type to hold cipher input and output blocks
IO(0 To BlkLenMax - 1) As Byte
End Type

Rem Change "d:\dll_pth" in the following lines to the directory path where the AES DLL is located
Private Declare Function AesBlkLen Lib "d:\dll_path\aes.dll" Alias "_aes_blk_len@8" (ByVal N As Long, C As AESctx) As Integer
Private Declare Function AesEncKey Lib "d:\dll_path\aes.dll" Alias "_aes_enc_key@12" (K As KeyBlk, ByVal N As Long, C As AESctx) As Integer
Private Declare Function AesDecKey Lib "d:\dll_path\aes.dll" Alias "_aes_dec_key@12" (K As KeyBlk, ByVal N As Long, C As AESctx) As Integer
Private Declare Function AesEncBlk Lib "d:\dll_path\aes.dll" Alias "_aes_enc_blk@12" (Ib As IoBlk, Ob As IoBlk, C As AESctx) As Integer
Private Declare Function AesDecBlk Lib "d:\dll_path\aes.dll" Alias "_aes_dec_blk@12" (Ib As IoBlk, Ob As IoBlk, C As AESctx) As Integer

Private Sub Hex(X As Byte) ' Output a byte in hexadecimal format
Dim H As Byte
H = Int(X / 16)
If H < 10 Then
Debug.Print Chr(48 + H);
Else
Debug.Print Chr(87 + H);
End If
H = Int(X Mod 16)
If H < 10 Then
Debug.Print Chr(48 + H);
Else
Debug.Print Chr(87 + H);
End If
End Sub

Private Sub OutKey(S As String, B As KeyBlk) ' Display a key value
Debug.Print: Debug.Print S;
For i = 0 To KeyLen - 1
Hex B.K(i)
Next i
End Sub

Private Sub OutBlock(S As String, B As IoBlk) ' Display an input/output block
Debug.Print: Debug.Print S;
For i = 0 To BlkLen - 1
Hex B.IO(i)
Next i
End Sub

Rem The following Main routine should output the following in the immediate window:
Rem Key = 00000000000000000000000000000000
Rem Input = 00000000000000000000000000000000
Rem Encrypted Text = 66e94bd4ef8a2c3b884cfa59ca342b2e
Rem Decrypted Text = 00000000000000000000000000000000

Sub Main()
Dim Key As KeyBlk ' These variables are automatically
Dim Ib As IoBlk, Ob As IoBlk, Rb As IoBlk
Dim Cx As AESctx ' initialised to zero values in VBA
Dim RetVal As Integer

BlkLen = 16: KeyLen = 16

Rem RetVal = AesBlkLen(BlkLen, Cx) ' include if the cipher block size is variable

OutKey "Key = ", Key
OutBlock "Input = ", Ib

RetVal = AesEncKey(Key, KeyLen, Cx) ' set an all zero encryption key
RetVal = AesEncBlk(Ib, Ob, Cx) ' encrypt Ib to Ob
OutBlock "Encrypted Text = ", Ob

RetVal = AesDecKey(Key, KeyLen, Cx) ' set an all zero decryption key
RetVal = AesDecBlk(Ob, Rb, Cx) ' decrypt Ob to Rb
OutBlock "Decrypted Text = ", Rb
Debug.Print

End Sub

Visual Basic for Applications code to illustrate the use of the AES Dynamic Link Library.

Visual Basic for Applications code to illustrate the use of the AES Dynamic Link Library. Very similar code should also work in Visual Basic.

Private Const BlkLenMax = 32 ' maximum block length in bytes

Private Const KeyLenMax = 32 ' maximum block length in bytes

Private Const KeySchLenMax = 128 ' maximum key schedule length in bytes

Private BlkLen As Integer ' actual block length

Private KeyLen As Integer ' actual key length

Private Type AESctx ' Type to hold the AES context data

Ekey(0 To KeySchLenMax - 1) As Long

Nrnd As Long

Ncol As Long

End Type

Private Type KeyBlk ' Type to hold user key data

K(0 To KeyLenMax - 1) As Byte

End Type

Private Type IoBlk ' Type to hold cipher input and output blocks

IO(0 To BlkLenMax - 1) As Byte

End Type

Rem Change "d:\dll_pth" in the following lines to the directory path where the AES DLL is located

Private Declare Function AesBlkLen Lib "d:\dll_path\aes.dll" Alias "_aes_blk_len@8" (ByVal N As Long, C As AESctx) As Integer

Private Declare Function AesEncKey Lib "d:\dll_path\aes.dll" Alias "_aes_enc_key@12" (K As KeyBlk, ByVal N As Long, C As AESctx) As Integer

Private Declare Function AesDecKey Lib "d:\dll_path\aes.dll" Alias "_aes_dec_key@12" (K As KeyBlk, ByVal N As Long, C As AESctx) As Integer

Private Declare Function AesEncBlk Lib "d:\dll_path\aes.dll" Alias "_aes_enc_blk@12" (Ib As IoBlk, Ob As IoBlk, C As AESctx) As Integer

Private Declare Function AesDecBlk Lib "d:\dll_path\aes.dll" Alias "_aes_dec_blk@12" (Ib As IoBlk, Ob As IoBlk, C As AESctx) As Integer

Private Sub Hex(X As Byte) ' Output a byte in hexadecimal format

Dim H As Byte

H = Int(X / 16)

If H <>

Debug.Print Chr(48 + H);

Else

Debug.Print Chr(87 + H);

End If

H = Int(X Mod 16)

If H <>

Debug.Print Chr(48 + H);

Else

Debug.Print Chr(87 + H);

End If

End Sub

Private Sub OutKey(S As String, B As KeyBlk) ' Display a key value

Debug.Print: Debug.Print S;

For i = 0 To KeyLen - 1

Hex B.K(i)

Next i

End Sub

Private Sub OutBlock(S As String, B As IoBlk) ' Display an input/output block

Debug.Print: Debug.Print S;

For i = 0 To BlkLen - 1

Hex B.IO(i)

Next i

End Sub

Rem The following Main routine should output the following in the immediate window:

Rem Key = 00000000000000000000000000000000

Rem Input = 00000000000000000000000000000000

Rem Encrypted Text = 66e94bd4ef8a2c3b884cfa59ca342b2e

Rem Decrypted Text = 00000000000000000000000000000000

Sub Main()

Dim Key As KeyBlk ' These variables are automatically

Dim Ib As IoBlk, Ob As IoBlk, Rb As IoBlk

Dim Cx As AESctx ' initialised to zero values in VBA

Dim RetVal As Integer

BlkLen = 16: KeyLen = 16

Rem RetVal = AesBlkLen(BlkLen, Cx) ' include if the cipher block size is variable

OutKey "Key = ", Key

OutBlock "Input = ", Ib

RetVal = AesEncKey(Key, KeyLen, Cx) ' set an all zero encryption key

RetVal = AesEncBlk(Ib, Ob, Cx) ' encrypt Ib to Ob

OutBlock "Encrypted Text = ", Ob

RetVal = AesDecKey(Key, KeyLen, Cx) ' set an all zero decryption key

RetVal = AesDecBlk(Ob, Rb, Cx) ' decrypt Ob to Rb

OutBlock "Decrypted Text = ", Rb

Debug.Print

End Sub

Your Title