3

I would like to convert a uint number to its binary representation, but have so far failed. What would be the best way to make it happen?

Thanks!

  • What do you men by failed so far? what have you tried? – Achala Dissanayake Mar 26 '18 at 13:42
1
contract Test {
    uint256 public integer = 100;
    uint256[] public array;

    function fill_array() {
        while (integer > 0) {
            uint256 bit = integer%2;
            uint256 quotient = integer/2;
            array.push(bit);
            integer = quotient;
        }
    }
}

If you really want to have an array of bools, you can do the following.

contract Test {
    uint256 public integer = 100;
    bool[] public array;

    function fill_array() {
        while (integer > 0) {
            bool bit = (integer%2) != 0;
            uint256 quotient = integer/2;
            array.push(bit);
            integer = quotient;
        }
    }
}

Although I would advise you to try to avoid to do such tasks because it's costly, especially as your integer gets bigger.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.