Saturday 23 March 2013

OOP344 Week 11: Binary String Function

The following function takes an integer and returns the binary string:

const char* bits(unsigned int val){
    unsigned int m = 1 << sizeof(val)*8-1;
    char* str = new char[sizeof(val)*8 + 1];
    int i = 0;
    while(m){
        str[i] = (val & m)?'1':'0';   
        i++;
        m = m >> 1;
    }
    str[i] = 0;
    return str;
}

No comments:

Post a Comment