Sunday, 11 November 2012

Week11_char *bits(unsigned int Val)

Output bits as a string:

char *bits(unsigned int Val){
// write the above function so it works like this:
// cout<<bits(2345)<<endl;
    char* bitstr = new char[sizeof(Val)*8];
    unsigned int m = 1 << (sizeof(Val)*8 - 1);
    int i =0;
    while (m) {
        bitstr[i] = 48 + (int)!!(Val & m);
        m = m >>1;
        i++;
    }
    bitstr[i]='\0';
    return bitstr;  
}

No comments:

Post a Comment