[C++] signed int の値がマイナスの場合に右シフトすると 32bit目は 1 が補完される

というメモ。つまり算術シフトってやつ

void printBinary(unsigned int dec)
{
  unsigned int c[32];

  unsigned int counter = 0;
  while (dec) {
    assert(counter < 32);
    c[counter++] = dec & 1;
    dec >>= 1;
  }

  char bin[32 + 1];
  memset(bin, '0', 32);

  unsigned int start = 32 - counter;
  while (counter--) {
    assert(counter < 32);
    assert(start < 32);
    bin[start++] = c[counter] ? '1' : '0';
  }

  bin[32] =  '\0';

  printf("%s\n", bin);
}

void test()
{
  signed int i;

  i = INT_MIN;
  printf("%d\n", i); // -2147483648
  printBinary(i);    // 10000000000000000000000000000000
  i >>= 1;
  printf("%d\n", i); // -1073741824
  printBinary(i);    // 11000000000000000000000000000000
  i >>= 1;
  printf("%d\n", i); // -536870912
  printBinary(i);    // 11100000000000000000000000000000

  i = INT_MIN + 1;
  printf("%d\n", i); // -2147483647
  printBinary(i);    // 10000000000000000000000000000001
  i <<= 1;
  printf("%d\n", i); // 2
  printBinary(i);    // 00000000000000000000000000000010

  i = INT_MAX;
  printf("%d\n", i); // 2147483647
  printBinary(i);    // 01111111111111111111111111111111
  i <<= 1;
  printf("%d\n", i); // -2
  printBinary(i);    // 11111111111111111111111111111110

  unsigned int u;

  u = INT_MIN;
  printf("%u\n", u); // 2147483648
  printBinary(u);    // 10000000000000000000000000000000
  u >>= 1;
  printf("%u\n", u); // 1073741824
  printBinary(u);    // 01000000000000000000000000000000
  u >>= 1;
  printf("%u\n", u); // -536870912
  printBinary(u);    // 00100000000000000000000000000000

  u = INT_MIN + 1;
  printf("%u\n", u); // 2147483649
  printBinary(u);    // 10000000000000000000000000000001
  u <<= 1;
  printf("%u\n", u); // 2
  printBinary(u);    // 00000000000000000000000000000010
}
Share