Monday 25 November 2013

CopyPattern from byte to integer

Advantages:
* Uses existing functions

using namespace std;
#include <iostream>

void setbit(int& val, int position, bool bitval) {
    val = (bitval ? (val | (1 << (position - 1))) : (val & ~(1 << (position - 1))));
}

void copypattern(char source, int& destination, int position) {
    int i;
    if ((position-1+8) < sizeof(int)*8) {
        for (i = position; i< (position - 1 + 9); i++) {
            setbit(destination, i, !!(source& 1 << (i-position)));
        }
    }
    else {
        cout << "Not enough space for copy, try another position" << endl;
    }
}

void prnBits(unsigned int val){
    for(unsigned int i = sizeof(int)*8; i--;cout<<!!(val & 1 << i));
}

int main() {
    int A = 0x000FFF;
    char B = 'a';
    prnBits(A);
    cout << endl;
    prnBits(B);
    cout << endl;
    copypattern(B,A,24);
    prnBits(A);
    cout << endl;
    getchar();
    return 0;
}

Wednesday 2 October 2013

BasicMath implementation

BasicMath implementation on C++

Advantages:
* Works with double
* Checks for incorrect input

Disadvantages:
* Uses namespace std. Big amount of libraries inside of it.

Code:

#include <iostream>
using namespace std;


int main(int argc, char* argv[]) {
    double result;
    double test;
    if ((argc != 4) || (strlen(argv[2]) != 1) || (sscanf_s(argv[1],"%d", &test) != 1) || (sscanf_s(argv[3], "%d", &test) != 1))
    {
        cout << "<number> <+-x/> <number><ENTER>\n";
        return 1;
    }
    else
    {
        if (argv[2][0] == '+')
            result = atof(argv[1]) + atof(argv[3]);
        else if (argv[2][0] == '-')
                    result = atof(argv[1]) - atof(argv[3]);
            else if (argv[2][0] == 'x')
                        result = atof(argv[1]) * atof(argv[3]);
                else if (argv[2][0] == '/')
                {
                        if (atof(argv[3]) == 0)
                        {
                            cout << "Divide by zero is not possible";
                            return 2;
                        }
                        else
                            result = atof(argv[1]) / atof(argv[3]);
                }
                else
                {
                        cout << "<number> <+-x/> <number><ENTER>\n";
                        return 1;
                }
        cout << result << "\n";
        return 0;
    }
}

Sunday 8 September 2013

Day one

Hey hey hey! It's first day of my blog. Lets see how it goes.