Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C++ compiler represent int numbers in binary code?

Tags:

c++

binary

I've written a program, which shows binary representation of a particular integer value, using bitwise operators in C++. For even numbers it works as I expect, but for odd it adds 1 to the left of the binary representation.

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
    unsigned int a = 128;

    for (int i = sizeof(a) * 8; i >= 0; --i) {
        if (a & (1UL << i)) { // if i-th digit is 1
            cout << 1;        // Output 1
        }
        else {
            cout << 0;        // Otherwise output 0
        }
    }
    cout << endl;

    system("pause");

    return 0;
}

Results:

  • For a = 128: 000000000000000000000000010000000,
  • For a = 127: 100000000000000000000000001111111
like image 298
Влад Казимиров Avatar asked Jul 09 '26 19:07

Влад Казимиров


1 Answers

  1. You might prefer CHAR_BIT macro instead of raw 8 (#include <climits>).
  2. Consider your start value! Assuming unsigned int having 32 bit, your start value is int i = 4*8, so 1U << i shifts the value out of range. This is undefined behaviour and could result in anything, obviously, your specific compiler or hardware shifts %32, thus you get an initial value & 1, resulting in the unexpected leading 1... Did you notice that you actually printed out 33 digits instead of only 32?
like image 110
Aconcagua Avatar answered Jul 11 '26 13:07

Aconcagua