HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Converting decimal integer to binary string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
decimalbinaryconvertingstringinteger

Problem

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>=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 > 0) {
        //% the dec number with the base 2 each time and if remainder>0 then set the bit
        remainder = dec % 2;
        dec /= 2;
        if (counter == y) {
            bin[counter] = '\0';
        }

        if (remainder > 0) {
            bin[(counter - 1)] = '1';
        }
        else {
            bin[(counter - 1)] = '0';
        }
        counter--;
    }
    return bin; 
}

Solution

What about taking the trailing zero out of the loop?

while (counter > 0) {

// ...

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


might look like this

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

while (counter > 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.

Code Snippets

while (counter > 0) {

// ...

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

while (counter > 0) {

// ...
char* DectoBin(unsigned dec) {

Context

StackExchange Code Review Q#131593, answer score: 2

Revisions (0)

No revisions yet.