Archyvas

Įrašo tag'ai: ‘c++’

C++. How to print non ASCII characters?

Rugsėjis 9th, 2009 Ernestas Kardzys 2 komentarai

We have some additional letters in the Lithuanian language: ą, č, ę, ė, į, š, ų, ū, ž (if you can’t see them – change the encoding of your browser into Unicode). The point is, that cout can not print those letters. So, how to print Unicode letters in the console?

The solution:

ernestas@ernestas-laptop:~$ g++ code.cpp
ernestas@ernestas-laptop:~$ ./a.out
Žuvis
Šamas
Paštas
ernestas@ernestas-laptop:~$ cat code.cpp
#include <iostream>
#include <fstream>
#include <wchar.h>
using namespace std;

void print(const wchar_t *text) {
wcout << text << endl;
}

int main() {
locale::global(locale(“en_US.utf8″));
wcout << L”Žuvis” << endl;
print(L”Šamas”);
wchar_t text[] = L”Paštas”;
print(text);

return 0;
}
ernestas@ernestas-laptop:~$

P.S. The translation:

Žuvis – The Fish
Šamas – The Sheatfish
Paštas – The Post

C#. Object -> Dictionary -> Object

Birželis 13th, 2009 Ernestas Kardzys 2 komentarai

I have the fallowing situation. I have an object. I need to make a Dictionary, which contains all the properties (and it’s values) of the object. Then send this Dictionary over the network. In client side the Dictionary will be received and then all the data from Dictionary will be put to an object.

It’s also possible to serialize an object and then send it over the network (without making a Dictionary object) but we decided that it’s better to make a Dictionary.

So, the code:

class PackageMaker
{
#region Methods

/// <summary>
/// Scans object and adds entries to a dictionary
/// </summary>
/// <param name=”serializableObject”>Object needs to be scanned</param>
/// <returns>Dictionary with properties and their values</returns>
public Dictionary<string, string> AddToPackage(Object serializableObject)
{
if (serializableObject == null)
throw new ArgumentNullException(“serializableObject is not initialized!”);

Dictionary<string, string> package = new Dictionary<string, string>();

foreach (PropertyInfo packetInfo in serializableObject.GetType().GetProperties())
{
package.Add(packetInfo.Name, packetInfo.GetValue(serializableObject, null).ToString());
}

return package;
}

/// <summary>
/// Extracts data from dictionary and sets the data to a object
/// </summary>
/// <param name=”packet”>Dictionary with properties and their values</param>
/// <param name=”deserializedObject”>Object which set values</param>
public void MakeObjectFromPackage(Dictionary<string, string> packet, Object deserializedObject)
{
if (deserializedObject == null)
throw new ArgumentNullException(“serializableObject is not initialized!”);

foreach (KeyValuePair<string, string> entry in packet)
{
if (deserializedObject.GetType().GetProperty(entry.Key) != null)
{
deserializedObject.GetType().GetProperty(entry.Key).SetValue(deserializedObject, entry.Value, null);
}
}
}

#endregion

}

It looks like it’s working :)

C#. Int array vs. ArrayList vs. Dictionary

Birželis 7th, 2009 Ernestas Kardzys 2 komentarai

private static void TestIntArray()
{
int [] array = new int[1000];
for (int i = 0; i < 1000; i++)
array[i] = i;
}

private static void TestArrayList()
{
ArrayList array = new ArrayList();
for (int i = 0; i < 1000; i++)
array.Add(i);
}

// Code….

long start = DateTime.Now.Ticks;
TestIntArray();
long end = DateTime.Now.Ticks;
Console.WriteLine(“Time with int array: {0}”, end – start);

long start2 = DateTime.Now.Ticks;
TestArrayList();
long end2 = DateTime.Now.Ticks;
Console.WriteLine(“Time with ArrayList array: {0}”, end2 – start2);

The result:

Time with int array: 30000
Time with ArrayList array: 10000

So, working with ArrayList is faster. Hm…

If we have multidimensional array and Dictionary<int, int> the difference is even bigger:

private static void TestIntArray()
{
int [ , ] array = new int[1000, 1000];
int i = 0;
for (int j = 0; j < 1000; j++)
array[i , j] = i++;
}

private static void TestDictionary()
{
Dictionary<int, int> array = new Dictionary<int, int>();
int i = 0;
for (int j = 0; j < 1000; j++)
array.Add(j, i++);
}

Time with int array: 60000
Time with Dictionary: 10000

Interesting :)

Point multiplication in Elliptic Curves

Gegužė 16th, 2009 Ernestas Kardzys Nėra komentarų

I was browsing the web for information about the binary multiplication (also known as “left-to-right multiplication”) in Ellipti curves. I wrote a demonstration of the algorithm. Unfortunately, it’s very brief version, but it might be interesting for someone :) This demonstration generates the right point multiplication sequency in binary multiplication of point.

First – very short theory. Point multiplication is the operation: Q = k∙P. Point multiplication is the combination of point doubling and point addition. The number k is converted into binary form and according to it’s value (0 or 1) the addition is performed or not. The simplest and the oldest is the binary multiplication method (also called “left to right point multiplication”). The algorithm:

Ø Input: A point P and l-bit integer k, where k = (k[l - 1]…k[1]k[0]), k[i] = {0, 1};

Ø Output: k∙P.

Ø Q = 0

Ø For j = l – 1 to 0 do

o Q = [2]Q

o If kj = 1, then Q = Q + P

Ø Return Q

So, we need to get the binary representation of our k. It can be done with & operator in C. The addition must be performed, if k[i] = 1 (condition: number & 1).

So, the demonstration code looks like that:

void sim_bmul(const long number) {
long no = number;
string line;
int p[sizeof(long) * 8];

/* Get binary digits */
int i = 0;
while(no > 0)
{
if (no & 1)
p[i++] = 1;
else
(p[i++] = 0);
no >>= 1;
}

i–;

while(i >= 0) {
/* Doubling emulation */
if (line.size() != 0)
line = line.insert(0, “(2″);
/* End of doubling emulation */

if (p[i] == 1) {
/* Addition simulation */
if (line.size() == 0)
line.insert(line.size(), “(P”);
else
line.insert(line.size(), ” + P”);
}

if (line.size() > 0)
line.insert(line.size(), “)”);

cout << line.c_str() << endl;

i–;
}

cout << line.c_str() << endl;
}

So, if we pass 11 (in binary: 1011) this demonstration should give us the following sentence: (2(2(2(P)) + P) + P).

Doubling emulation looks quite weird, but at the moment I could find a better solution. Well, next time…

Nice ;)

Using interfaces in C#

Balandis 23rd, 2009 Ernestas Kardzys 2 komentarai

Simple example with interfaces. This example just shows, that when we have interface (method’s signatures, delegates etc.) we don’t care, how this interface is implemented.

We have interface and class:

interface IList
{
void Add(object o);
void Remove(object o);
void Print();
}

class Implementation : IList
{
private ArrayList arrayList = new ArrayList();

public void Add(object o)
{
arrayList.Add(o);
}

public void Remove(object o)
{
arrayList.Remove(o);
}

public void Print()
{
foreach (string line in arrayList)
Console.WriteLine(line);
}

}

Somewhere in the code we have methods:

void Foo(IList list)
{
list.Add(“I”);
list.Add(“am”);
list.Add(“using”);
list.Add(“interfaces”);
}

void Foo2(IList list)
{
list.Print();
}

And we call them:

IList list = new Implementation();
Foo(list);
Foo2(list);

Try to guess, what is the output? ;)

Passing parameters in C#

Balandis 22nd, 2009 Ernestas Kardzys 3 komentarai

In C we can use a function printf(), which can take different numbers of parameters. E.g.: printf(“%d %s”, a, b). How this can be done in C#?

It can be done by keyword params:

int Method(params int[] var)
{
int sum = 0;
foreach (int i in var)
sum += i;
return sum;
}

// Code…

Method(5, 2, 3);

Method(64, 1);

Method(9);

More information: http://msdn.microsoft.com/en-us/library/w5zay9db(VS.71).aspx

Multiple-Precision Modular Arithmetics. Addition

I was browsing (ok, lets be honest – Goooogling) the web in order to find some Multiple-Precision Modular Arithmetics algorithms. Our lecturer recomended a very good book – “Handbook of Applied Cryptography“. So, I used this book in order to code my algorithms (modular addition, subraction and multiplication) :)

So, here is my modular addition algorithm implementation in the C programming language.

// Name: int MultiplePrecisionAddition()
// Input:        x        – first integer, size n
//                y        – second integer, size n
//                n        – number of digits in x, y, w
//                base    – modulus
// Output:        w        – result, size n, w[n - 1]…w[0]
// Description: Calculates (x + y mod base)
int MultiplePrecisionAddition(int x[], int y[], int w[], int n, int base) {
int i = 0, c = 0, result = 0, temp = 0;
for (i = 0; i < n – 1; ++i) {
result = x[i] + y[i] + c;
w[i] = result % base;
result < base ?    c = 0 : c = 1;
}
w[n - 1] = c;

// Converts from w[0]w[1]…w[n - 1] to w[n - 1]…w[0]
for (i = 0; i < n / 2; ++i) {
temp = w[i];
w[i] = w[n - 1 - i];
w[n - 1 - i] = temp;
}
return 0;
}

Any suggestions how to improve my code? ;)

C#. Howto get information about class members dynamicaly

Last weekend I had a problem. I have two different classes:

class ClassWithData2
{
public ClassWithData2()
{
}

private string _Field;
public string Field
{
get { return _Field; }
set { _Field = value; }
}

}

class ClassWithData
{
public ClassWithData()
{
}

private string _Name = null;
public string Name
{
get { return _Name; }
set { _Name = value; }
}

private string _Age;
public string Age
{
get { return _Age; }
set { _Age = value; }
}

}

My problem was: how to pass those two classes to one method and then print what members do they have and what values the class members do have. The code is as follows:

using System.Reflection;

// Code…

private void Print<T>(T packet)
{
foreach (PropertyInfo packetInfo in packet.GetType().GetProperties())
{
Console.WriteLine(packetInfo.Name + ” ” + packetInfo.GetValue(packet, null));
}
}

Kategorijos:Programavimas Raktažodžiai:, , ,

C#. Gijų panaudojimas

Gruodis 4th, 2008 Ernestas Kardzys 3 komentarai

Bandžiausi .NETo galimybes – kaip su gijomis draugaujama. Nedidelę programėlę parašiau :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestineProgramaConsole
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
Thread myThread = new Thread(CoolClass.CoolThread);
myThread.Start();
}
Console.ReadLine();
}

}

class CoolClass
{
private static object lockThread = new object();
public CoolClass() { }

public static void CoolThread()
{
lock (lockThread){
Random generator = new Random();
List<int> numbers = new List<int>();
for (int i = 0; i < 10; i++)
numbers.Add(generator.Next(10));

PrintList(numbers, “[*] Gijos masyvas: “);
}
}

private static void PrintList(List<int> numbers, string text)
{
Console.WriteLine(text);
for (int i = 0; i < numbers.Count; i++)
Console.Write(numbers[i] + ” “);

Console.WriteLine();
}
}
}
Lock duoda sinchronizaciją – išmeskit ir galėsit mėgautis vaizdu, kaip kelios gijos vienu metu bando spausdinti :)

C# Remote Object’o iškvietimas

Spalis 30th, 2008 Ernestas Kardzys 2 komentarai

KTU’ne per .NET modulį davė parašyti dvi programėles. Viena iškviečia kitos Remote Object’ą. Kitaip tariant: veikia programa-serveris. Jinai turi žiauriai gerą ir naudingą metodą, kuriuo baisiai nori pasinaudoti programa-klientas. Kaip tai padaryti?

//———–RemoteServer.cs————————–

using System;
using System.Runtime;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PirmasAtsiskaitymas
{
    public class RemoteServer : MarshalByRefObject
    {
        public RemoteServer() { }

        static void Main(string[] args)
        {
            HttpChannel chan1 = new HttpChannel(10000);

            ChannelServices.RegisterChannel(chan1);

            RemotingConfiguration.RegisterWellKnownServiceType(
                typeof(PirmasAtsiskaitymas.RemoteServer),
                "GrazintiSkaiciu",
                WellKnownObjectMode.Singleton);

            Console.ReadLine();
        }

        public int GrazintiSkaiciu()
        {
            Random random = new Random();
            int skaicius = random.Next();
            return skaicius;
        }
     }

}
//-----------------Program.cs--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using System.IO;
namespace PirmasAtsiskaitymas
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpChannel chan1 = new HttpChannel();
            ChannelServices.RegisterChannel(chan1);
            RemoteServer serveris =
                   (RemoteServer)Activator.GetObject(typeof(PirmasAtsiskaitymas.RemoteServer),
                   "http://localhost:10000/GrazintiSkaiciu");

            try
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("Nutoles serveris grazino: " + serveris.GrazintiSkaiciu());
                }
            }
            catch (IOException ex)
            {
                Console.WriteLine("Priemimo klaida!!!!");
            }
        }
    }
}

Kompiliavimas:
csc RemoteServer.cs
csc /reference:RemoteServer.exe Program.cs
Tada paleidžiame RemoteServer.exe ir Program.exe.
Na, ir žiūrim, ką šis programinės minties stebūklas pagamins :)