agraja.wordpress.com

Posts Tagged ‘C’

System Verilog Singleton Example

In Cpp, SystemVerilog on October 3, 2008 at 5:43 am

Purpose of a singleton:
To have a class which has only one instance(object)
All the objects of this class refer to same global object
that is created only once
This design pattern provides a mechanism for providing
namespaces to global variables

Download here. singleton-design-pattern
C++ example for singleton design pattern: click here

System Verilog example for singleton design pattern

// Filename  : singleton.sv
// Author    : A.G.Raja
// License   : GPL
// Website   : http://agraja.wordpress.com

module tb;

class Singleton;
// object that is created only once
extern static Singleton single;
// constructor that is called only once
extern function new;
// method to get object
extern function Singleton get_instance;
// data to check the functionality
int data;
endclass

initial Singleton::single = null;

function Singleton::new;
data = 14;
endfunction

function Singleton Singleton::get_instance;
// call the constructor for the first time
// if the object has been created already
// return reference to the object already created
if(single==null) single = new;
// return the reference to the object
return single;
endfunction

Singleton s, t;

initial begin
// don’t use s= new;
// since it will create new instances
// instead use the get_instance method
s = s.get_instance();
t = t.get_instance();
$display(“initial value of s.data  = “,s.data);
s.data = 25;
$display(“modified value of s.data = “,s.data);
$display(“value of t.data          = “,t.data);
end
endmodule

Result:
initial value of s->data  = 14
modified value of s->data = 25
value of t->data          = 25
Download here. singleton-design-pattern

C++ Singleton Example

In Cpp on October 3, 2008 at 5:40 am

Download here.  singleton-design-pattern

Purpose of a singleton:
To have a class which has only one instance(object)
All the objects of this class refer to same global object
that is created only once
This design pattern provides a mechanism for providing
namespaces to global variables

C++ example for singleton design pattern

// Filename  : singleton.cpp
// Author    : A.G.Raja
// License   : GPL
// Website   : http://agraja.wordpress.com

#include <iostream>

using namespace std;

class Singleton {
// constructor that is called only once
Singleton();
// object that is created only once
static Singleton *single;
public:
// method to get object
Singleton* get_instance();
// data to check the functionality
int data;
};

Singleton* Singleton::single = NULL;

Singleton* Singleton::get_instance() {
// call the constructor for the first time
// if the object has been created already
// return reference to the object already created
if(single==NULL) single = new Singleton();
return single;
}

Singleton::Singleton() {
data = 14;
}

int main() {
Singleton *s, *t ;
s = s->get_instance();
cout<<”initial value of s->data  = “<<s->data<<endl;
s->data = 25;
cout<<”modified value of s->data = “<<s->data<<endl;
t = t->get_instance();
cout<<”value of t->data          = “<<t->data<<endl;
}
// end of file singleton.cpp

Result:
initial value of s->data  = 14
modified value of s->data = 25
value of t->data          = 25

Download here.  singleton-design-pattern

C++ string, wstring conversion functions

In Cpp on September 8, 2008 at 6:15 am

Download here. string-wstring-conversion-functions

// Filename    : string_wstring.cpp
// Author      : A.G.Raja
// License     : GPL
// Website     : http://agraja.wordpress.com

#include <iostream>

using namespace std;

string wstring2string(wstring wstr) {
string str(wstr.length(),’ ‘);
copy(wstr.begin(),wstr.end(),str.begin());
return str;
}

wstring string2wstring(string str) {
wstring wstr(str.length(),L’ ‘);
copy(str.begin(),str.end(),wstr.begin());
return wstr;
}

int main() {
wstring wstr = string2wstring(“raja”);
string str = wstring2string(wstr);
cout<<str<<endl;
}

Download here. string-wstring-conversion-functions

C++ String Getline Class

In C on August 18, 2008 at 11:14 am

Download here. getline

Features of the below string getline class

1) Can be used like getline function for streams

2) Can have multiple delimiters as opposed to the getline function for streams

3) Delimiter need not be single char. It can be a string

4) Pointer to current position in the string is automatically incremented

similar to that in stringstream

5) It is possible to rewind the pointer position to zero using the rewind() method.

6) It is also possible to get single char at the current position of pointer from the string

7) It is possible to get single char at current pointer position if it is one of the

characters of the list.  This is an optional argument to the get method

8) stream getline feature can be realized by calling the getline method of this

class without passing any arguments. No arguments to getline method defaults to

newline char as delimiter

// File : Getline.hh
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com

#include <iostream>

using namespace std;

class Getline {
string text, buffer;
int pos,p;
public:
int str(string txt) {
pos = 0;
this->text = txt;
}
string getline(string delim = “\n”, int delim_type = 1);
char get(string delim = “”);
int unget(int decr = 1) {
pos -= decr;
}
int end() {
if(pos>=text.size()) return 1;
else return 0;
}
int rewind() {
pos = 0;
}
};

string Getline::getline(string delim, int delim_type) {
p = delim_type ? text.find(delim,pos)
: text.find_first_of(delim,pos);
if(p!=-1) {
buffer = text.substr(pos,p-pos);
pos = delim_type ? p+delim.length() : p +1;
} else {
buffer = text.substr(pos);
pos += buffer.length();
} return buffer;
}

char Getline::get(string delim) {
if(delim.empty() and pos<text.size()) return text[pos++];
if(delim.find(text[pos])!=-1) {
pos++;
return text[pos-1];
}
return 0; // must
}

// End of File Getline.hh

// File : test_Getline.cpp
// Author : A.G.Raja
// License : GPL
// Website : http://agraja.wordpress.com

#include <iostream>
#include “Getline.hh”

using namespace std;

int main() {
Getline g;
g.str(“Hi, my name is Raja\nI’m an Engineer”);
// Get the substring terminated by “y na”
cout<<g.getline(“y na”)<<endl;
// Result: “Hi, m”

// Get substring terminated by first of “sji”
cout<<g.getline(“sji”,0)<<endl;

// Get line terminated by ‘\n’
cout<<g.getline()<<endl;
// Result: “s Raja”

// Get single char at current position of pointer
cout<<g.get()<<endl;
// Result: “I”

// Get a char at current position of pointer
// if it is in the list “_$%’#”
cout<<g.get(“_$%’#”)<<endl;
// Result: “‘”

// Unget single char, unget 4 chars
g.unget(); g.unget(4);
}

Download here. getline

Perl script to display comments

In Bookmarks on March 19, 2008 at 1:57 pm

Download here. c_help.pdf

 

#!/usr/bin/perl

# Filename: chelp.pl

# Author : A. G. Raja

# Website : agraja.wordpress.com

# License : GPL

# pass c file as argument to this script

# this script displays all the comments

use strict;

use warnings;

open(FILE,$ARGV[0]) or die “File not Found”;

my $line;

my $start=0;

while ( $line = <FILE> ) {

if($line =~ /\/\//)

{

$line=~ s/(.*)\/\/(.*)/$2/;

print $line;

}

if($line =~ /\/\*/)

{

$start=1;

$line=~ s/(.*)\/\*(.*)/$2/;

}

if($line =~ /\*\//)

{

$line=~ s/(.*)\*\//$1/;

print $line;

$start=0;

}

if($start) { print $line; }

}

close FILE;

 

Tips:

Use a shell script to redirect the output

of the above script to another program.

Example

#!/bin/bash

# Filename: help.sh

# Author : A.G.Raja

# Website : agraja.wordpress.com

# License : GPL

# rename chelp.pl to chelp

# Install chelp and add to path

chelp $1 | less

Demo:

 

Below is a C file

 

// Filename : demo.c

// Author : cfile.pl

// License : GPL

#include <stdio.h>

#define print(x) printf(“str=%s\n”,x);

int main(int argc, char **argv)

{

/* this is a multi-

line comment */

char *str=”File name:”;// this will print file name

print(argv[0])

return 0;

}

 

Type at the terminal:

[raja@agraja ]$ chelp demo.c

 

The following will be printed to stdout

 

Filename : demo.c

Author : cfile.pl

License : GPL

this is a multi-

line comment

this will print file name

Download here. c_help.pdf

C Find Replace Program

In Bookmarks on March 19, 2008 at 1:35 pm

Download here. string_replace.pdf

// Filename : string_replace.c

// Author : A.G.Raja

// Website : agraja.wordpress.com

// License : GPL

#include <stdio.h>

 

 

char* string_replace(unsigned char *from, char *find, char *replace)

{

const char *p;

char *q, *to;

int i,d, match;

to=malloc(sizeof(char)*strlen(from)*strlen(replace)/strlen(find));

 

for(p = from, q = to; *p != ”; p++)

{

// find logic

for(d=0;d<strlen(find);d++)

{

if (*(p+d) == *(find+d)) match=1;

else match =0;

}

// replace logic

if (match)

{

for(i=0;i<strlen(replace);i++)

{

*(q+i)=*(replace+i);

}

q=q+i; p=p+d-1;

}

else // copy unchanged chars

{ *q=*p; q++; }

 

} *q = ”;

return to;

}

 

 

 

 

 

 

 

 

 

 

// Test code

int main()

{

unsigned char *str = “this is original text” ;

char f[]=”original”;

char r[]=”new”;

unsigned char *str2;

printf(“before:%s\n”,str);

str2=string_replace(str,f,r);

printf(“after:%s\n”,str2);

return 0;

}

 

Download here. string_replace.pdf

Tips:

See the following pages for char replace, trim spaces

char replace

trim spaces

 

C Find and Replace program

In Bookmarks on March 12, 2008 at 5:42 am

Download here. find_replace.pdf

// Filename : find_replace.c

// Author : A.G.Raja

// Website : agraja.wordpress.com

// License : GPL

#include <stdio.h>

void find_replace(char *to, unsigned char *from, char find, char replace)

{

const char *p; char *q;

for(p = from, q = to; *p != ”; p++)

{

if ( *p != find)

{ *q=*p; q++; }

else

{ *q=replace; q++; }

} *q = ”;

}

int main()

{

unsigned char *str = “this is original text” ;

unsigned char str2[strlen(str)];

printf(“before:%s\n”,str);

find_replace(str2,str,’s’,'x’);

printf(“after:%s\n”,str2);

return 0;

}

 

 

// This program can be used for single char only.

// string with more than one char is not supported

Download here. find_replace.pdf

Tips:

This function can be used to trim white spaces in file.

See this page for an example: Trim

See this page for string replace: string replace

 

 

 

 

System Verilog DPI Example

In Bookmarks on February 20, 2008 at 4:47 am

Refer to the previous post for introduction.

System Verilog DPI NCVerilog

The above example gives a demo with NCVerilog.

Here is the run script for running the same example with Modelsim under windows.

Download here. system-verilog-dpi-modelsim.pdf

#File name run.tcl

# Author: A.G.Raja

# Website: agraja.wordpress.com

# License: GPL

#Type at Transcript terminal: source run.tcl

vlib work

vlog -sv -dpiheader dpiheader.h dpi_top.v

exec gcc -c -g -IE:/modelsim/include dpi_main.c -o dpi_main.obj

exec gcc -shared -o dpi_main.dll dpi_main.obj -LE:/modelsim/win32

vsim -novopt top -sv_lib dpi_main

run

# EOF run.tcl

Replace “E:/modelsim” with “modelsim installation path”

1) Don’t create a new project while starting Modelsim

2) Open and proceed directly to Modelsim.

3) At the transcript terminal change to the working directory

4) No need to create a folder named work.

5) The run script given above does it.

Download here. system-verilog-dpi-modelsim.pdf

Download NCVerilog demo here.
 systemverilogdpi.pdf

 

C/C++ Assertions

In Bookmarks on February 4, 2008 at 10:29 am
// assert.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
// Licence: GPL
#include <iostream>
using namespace std;
#define my_assert(x) \
if(!x) cout<<__FILE__<<”:assertion on line “; \
cout<<__LINE__<<” failed”<<endl;
int main()
{
int a,b;
a=0;
my_assert(a) // User defined assertion
assert(a); // Predefined assertion
}
// g++ assert.cpp
Download here.
assert.doc

C++ File Operations

In Bookmarks on February 4, 2008 at 9:50 am
// file_write.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile (“example.txt”);
if (myfile.is_open())
{
myfile << “This is a line.\n”;
myfile << “This is another line.\n”;
myfile.close();
}
else cout << “Unable to open file”;
return 0;
}
// g++ file_write.cpp
// file_read.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile (“example.txt”);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << “Unable to open file”<<endl;
return 0;
}
//g++ file_read.cpp
Download here.
cpp_file_operations.doc

C++ Constructor Destructor

In Bookmarks on February 4, 2008 at 6:14 am

// constructor_destructor.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
// Licence: GPL

#include <iostream>
using namespace std;
class Employee{
char *name;
int age;
double salary;
public: Employee(); //Constructor
void print();
void setval(char *name, int age, double salary);
char* getname() { return name; }
int getage() { return age; }
double getsalary() { return salary; }
~Employee(); //Destructor
};

Employee::Employee()
{
cout<<”Object Created”<<endl;
name=”fresher”;
age=23;
salary=17500;
}
void Employee::print()
{
cout<< name<<”\t”<<age<<”\t”<<salary <<endl;
}
void Employee::setval(char *n, int a, double s)
{
name=n;
age=a;
salary=s;
}

Employee::~Employee()
{
cout<<”Object Destroyed”<<endl;
}

int main()
{
char *NAME;
int AGE;
double SALARY;
//Employee E257 = {“raja”,25,23519.78};
Employee E257;
cout<<”Print Default Values”<<endl;
E257.print(); // Default Values
E257.setval(“raja”,25,23768);
cout<<”Print New Values”<<endl;
E257.print(); // New values
NAME=E257.getname();
AGE=E257.getage();
SALARY=E257.getsalary();
cout<<NAME<<”\t”<<AGE<<”\t”<<SALARY<<endl;
}
// g++ constructor_destructor.cpp

Download here.

constructor.doc

C++ struct vs class

In Bookmarks on February 2, 2008 at 6:26 am
This is an example to show the similarity between a struct and a class

  #include <iostream>using namespace std;

int main()

{

struct employee

{char *name;

int age;

double salary;

};

employee e257 = {”raja“,25,23519.78};

cout<< e257.name<<”\t”<<e257.age

<<”\t”<<e257.salary <<endl;

class Employee { public:      char *name;
     int age;double salary; };

Employee E257 = {”raja”,25,23519.78};

cout<< E257.name<<”\t”<<E257.age

<<”\t”<<E257.salary <<endl;

}
Note:
1) All members of a struct are public by default
2) All members of a class are private by default
3) For a class member to be public, it has be
declared public with the keyword "public".
Advantage of using classes
1) Member variables are private and protected.
2) Constructors functions(declared public) can be
used  to initialize and modify values of that private variables.
See this page for Constructors:  Constructors & Destructors </pre
 Download here.struct.doc

C program to trim blank spaces

In C, Linux on December 13, 2007 at 6:50 am

#include <stdio.h>

void copy(char *to, char *from);

int main(void)
{

char str[80];

copy (str,” this ia a test “);

printf(“without spaces:%s”,str);

return 0;

}

void copy(char *to, char *from)

{

const char *p; char *q;

for(p=from,q=to;*p != ‘ ‘; p++)

// space between quotes in the above statement
{

if (*p != ‘ ‘) { *q=*p; q++; }

}

*q = ”;

}

// Download here.

// trim.doc

Tips: This function can be modified to find and replace a char.

See this page for an example Find and Replace

See this page for string replace: string replace

C command line arguments

In C on September 6, 2007 at 12:07 pm
#include <stdio.h>

int main(int argc, char *argv[])
{
    int x;

    printf("%d\n",argc);
    for (x=0; x<argc; x++)
        printf("%s\n",argv[x]);
    return 0;
}

C File Operations

In C on August 24, 2007 at 6:53 am
////////   file_operations.c  ////////
 #include <stdio.h>
 int main(void)
 {
 char temp[100];
 FILE *write_to_file = fopen("file.txt","w");
 fprintf(write_to_file,"%08x",0xC12E3A4);
 fclose(write_to_file);
 FILE *read_from_file = fopen("file.txt", "rb");
 fscanf(read_from_file,"%s",temp);
 printf("String read from file=%sn",temp);
 fclose(read_from_file);
 return 0;
 }

[raja@AGRAJA ~]$ gcc -Wall file_operations.c
[raja@AGRAJA ~]$ ./a.out

String read from file=0c12e3a4

Download here:

c_file_operations.doc

Pointers in C – Easy way to remember

In C, Linux on February 21, 2007 at 7:54 am
//          pointer_example.c
#include <stdio.h>
int main(void)
{
int k;                 // variable type declaration
k = 2;                // assignment statement
//          2 is rvalue (value in the right hand side of "=")
//          k is lvalue (value in the left hand side of "=")
int *ptr;              // pointer to store integer values
ptr = &k;           // address of k
//          *ptr is rvalue
//          ptr is lvalue
printf("value stored in k is %d\n", *ptr);
return(0);
//          k is name of variable;  k is an unmodifiable lvalue
//          ptr is name of address; ptr is a modifiable lvalue
}
//          value stored in k is 2

/* The size of memory required to store an address depends on the system. Some computers might require special handling to hold a segment and offset under certain circumstances. The actual size required is not too important so long as we have a way of informing the compiler that what we want to store is an address. Such a variable is called a pointer variable.

1) To store a variable, we need to know how many bits/bytes would be required to hold the value.

2) To store address of a variable, we need not know the number of bits/bytes would be required to hold the address. It is machine dependent.

3) Type declaration for a pointer indicates what type of variable will be stored in that address.

*/

/* Pointers vs Arrays

// In C a string is an array of characters terminated with a binary zero character

(written as slash0.JPG).

char my_string[40];

my_string[0] = ‘T’;

my_string[1] = ‘e’;

my_string[2] = ‘d’:

my_string[3] = ‘slash0.JPG‘;

// C permits

my_string[40] = “Ted”;

/* In the above example, my_string has 37 null characters in it, since the size of the array is 40 which is a constant. Here the lvalue is unmodifiable.

This can be avoided if a pointer is used instead. Here the lvalue is modifiable.

*/

//	Pointers to structures
typedef struct student
 {
 int age;
 int studentNumber;
 float averageGrade;
 char name[32];
 } STUDENT;
int main()
 {
 //a STUDENT variable
 STUDENT mary;
 //a pointer to a STUDENT variable
 STUDENT *pupil;
//assign some values
 mary.age = 14;
 mary.studentNumber = 5678;
 mary.averageGrade = 73;
//tell pupil to point at mary
 pupil = &mary;
//Notice in the examples below the use of -> instead of (*pupil).age
//we can now access members of the mary structure using the pupil pointer
 printf("Mary's student number is %d\n", pupil->studentNumber);
//we can also do assignment and all other normal variable operations
 pupil->averageGrade = 86.2;
printf("Mary's average grade is %f\n", mary.averageGrade);
return 0;
}

 Download here.

 pointers.doc