0

This only happens on a 64-bit system.

#include <iostream>

void printBits(unsigned long code) {
    long bit = (sizeof(code) * 8) - 1;

    std::cout << code << std::endl;

    while (bit >= 0) {
        bool value = code & (1 << bit--);

        std::cout << value;
    }

    std::cout << std::endl;
}

int main() {
    printBits(12345);
    return 0;
}

Here's the output on a 64-bit system (repeated twice);

0000000000000000001100000011100100000000000000000011000000111001

Here's the output compiled with -m32 (correct);

00000000000000000011000000111001

What's the reason for this and how can I correct it?

Jack Wilsdon
  • 6,706
  • 11
  • 44
  • 87
  • 2
    You should do some debugging - for example, what are the values of `bit` over time? – Oliver Charlesworth Jan 20 '18 at 18:42
  • 2
    Have you stepped through the code yet? Does it actually walk the `while` twice when run without the `-m32` flag? – Forty3 Jan 20 '18 at 18:42
  • 1
    I have to say - the claim of duplicity is a bit misleading. Yes, the answer to OP's question can be found in the referenced question - but shouldn't we allow for the possibility that the OP didn't realize he was using an `int` (1) while attempting to shift beyond 31 in his `long`? – Forty3 Jan 20 '18 at 19:12

0 Answers0