Converting decimal integer to binary string I'm wondering how I can make this function better, more compact, even faster. 

char* DectoBin(int dec) {
    int counter = 0;
    int x =0;
    while (dec&gt;=x) {
        counter++;
        x = pow(2, counter);
    }
    //counter is the # of bits in the converted binary number
    char* bin = new char[counter+1];
    //+1 for nul byte
    int y = counter;
    int remainder = 0;

    while (counter &gt; 0) {
        //% the dec number with the base 2 each time and if remainder&gt;0 then set the bit
        remainder = dec % 2;
        dec /= 2;
        if (counter == y) {
            bin[counter] = '\0';
        }

        if (remainder &gt; 0) {
            bin[(counter - 1)] = '1';
        }
        else {
            bin[(counter - 1)] = '0';
        }
        counter--;
    }
    return bin; 
}
What about taking the trailing zero out of the loop?

while (counter &gt; 0) {

// ...

    if (counter == y) {
        bin[counter] = '\0';
    }


might look like this

bin[counter] = '\0';
--counter;

while (counter &gt; 0) {

// ...


and you don't need int y anymore.

Also --counter might be tiny bit faster than counter-- in case your optimizer is not going to help you.



As the code is not dealing with negative values I guess

char* DectoBin(unsigned dec) {


would be more appropriate.