The irresistable source.

Lab 6

1. This is a program to pack/unpack 4 characters to/from a long integer. The packing algorithm uses a mask to clear the bits at the position of the integer where the character is to be inserted before performing a bitwise or on the integer and the character. This process is repeated until the entire integer is packed with the user’s data. The unpacking algorithm works the same way except the mask is inverted and it copies from the integer instead of to it.

2. Code

#include
#include

using namespace std;

unsigned long Pack(unsigned char, int, unsigned long);
unsigned char UnPack(int, unsigned long);

int main(void){
    const int LENGTH = 4;

    unsigned long packed_data;
    unsigned char c;
    int choice;
    bool done = false;

    do{
        cout << "Menu:" << endl;
        cout << "1.Pack Data" << endl;
        cout << "2.Unpack Data" << endl;
        cout << "3.Exit" << endl;
        cout < ";
        cin >> choice;
        switch(choice){
            case 1:
                cout << "Enter 4 characters: ";
                for(int i=0; i> c;
                    packed_data = Pack(c, LENGTH - (1+i), packed_data);
                }
                cin.ignore(numeric_limits::max(), '\n');
                cout << "Packed long integer is: " << hex << packed_data << endl;
                break;
            case 2:
                cout <> hex >> packed_data;
                cout << "Packed Characters are: ";
                for(int i=0; i<LENGTH; i++){
                    cout << UnPack(LENGTH - (1+i), packed_data);
                    if( i!= (LENGTH-1) ){
                        cout << " ";
                    }
                }
                break;
            default:
                done = true;
        }
        cout << endl;
    }while(!done);

    return 0;
}

unsigned long Pack(unsigned char c, int index, unsigned long packed_data){

    unsigned long mask;

    //cout << "Packing: " << c << " into byte " << index+1 << " of " << hex << packed_data << endl;

    mask = 0xFF;                        //Fill one byte with 1's.
    mask <<= index * 8;                 //Shit byte to the position to insert.
    mask = ~mask;                       //Invert so only the byte at position is zeroed out.
    packed_data &= mask;                //Zero out the byte in the position of packed data.
    packed_data |= ((unsigned long)c) << index*8;

    return packed_data;
}

unsigned char UnPack(int index, unsigned long packed_data){

    unsigned char c;
    unsigned long mask = 0xFF;
    mask <>= index * 8;
    c = packed_data;

    return c;
}

3. Screenshots

lab6

Leave a Reply

Your email address will not be published. Required fields are marked *