0

I want to encode the integer like 83 to binary code like 1100101 what is the fastest way to do that? now I'm using this code:

ToBinary(int size, int value) {  
    size--;  
    this->code = new bool[size];  
    int in = size;  
    while (in >= 0) {  
        if(pow(2, in) <= value) {  
        this->code[size-in] = pow(2, in);  
        value -= pow(2, in);  
        } else   
            this->code[size-in] = 0;  
        in--;  
    }  
}
4
  • 2
    That's a rather awkward way to do it. Simpler by far (and easier to understand) is to create a mask variable with 0x0001 in it and then shift that value one position at a time and AND with the input value. Test the result of the AND to set your bool or not. Commented Sep 16, 2012 at 14:19
  • for(int idx = 0; idx <= size; ++idx) { this->code[size - idx] = !!(value & (1 << idx)); } Commented Sep 16, 2012 at 14:19
  • You can also use either std::vector<bool> or better boost::dynamic_bitset<> Commented Sep 16, 2012 at 14:26
  • thx guys, helped, i have a dumb question :D how to vote as Useful comment :D? Commented Sep 16, 2012 at 16:03

2 Answers 2

3

You could take advantage of shifting using >> to make things a lot easier:

ToBinary(int size, int value) {
    int i = size;

    this->code = new bool[size];

    while(i--) {
        this->code[i] = (value >> i) & 1;
    }
}

(Or, to have it in the opposite order, this->code[size - i].)

Sign up to request clarification or add additional context in comments.

Comments

1

If you know the size at compile time, std::bitset<size> bits(value); will do what you want in its constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.