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;
}

No comments:

Post a comment