落書きノート

ふと自分が気になった事を書いてます

C言語で問題を解く

解きながら学ぶC言語

解きながら学ぶC言語

// q7-1
#include <stdio.h>
#include <limits.h>

int main(void) {
  printf("char : %d~%d\n", CHAR_MIN, CHAR_MAX);
  printf("signed char : %d~%d\n", SCHAR_MIN, SCHAR_MAX);
  printf("unsigned char : %d~%d\n", 0, UCHAR_MAX);
  printf("short int : %d~%d\n", SHRT_MIN, SHRT_MAX);
  printf("unsigned short int : %u~%u\n", 0, USHRT_MAX);
  printf("int : %d~%d\n", INT_MIN, INT_MAX);
  printf("unsigned int : %u~%u\n", 0, UINT_MAX);
  printf("long int : %ld~%ld\n", LONG_MIN, LONG_MAX);
  printf("unsigned long int : %lu~%lu\n", 0, ULONG_MAX);
  return 0;
}

// q7-2
#include <stdio.h>

int main(void) {
  printf("sizeof(char) == %u\n", (unsigned)sizeof(char));
  printf("sizeof(signed char) == %u\n", (unsigned)sizeof(signed char));
  printf("sizeof(unsigned char) == %u\n", (unsigned)sizeof(unsigned char));
  printf("sizeof(short int) == %u\n", (unsigned)sizeof(short int));
  printf("sizeof(unsigned short) == %u\n", (unsigned)sizeof(unsigned short));
  printf("sizeof(int) == %u\n", (unsigned)sizeof(int));
  printf("sizeof(unsigned) == %u\n", (unsigned)sizeof(unsigned));
  printf("sizeof(long int) == %u\n", (unsigned)sizeof(long int));
  printf("sizeof(unsigned long) == %u\n", (unsigned)sizeof(unsigned long));
  return 0;
}

// q7-3
#include <stdio.h>
#include <limits.h>

int main(void) {
  printf("この処理系のchar型は");
  if(CHAR_MIN)
    puts("符号付きで、");
  else
    puts("符号なしで、");
  printf("%d~%dを表すことが出来ます。\n", CHAR_MIN, CHAR_MAX);
  return 0;
}

// q7-4
#include <stdio.h>
#include <limits.h>

int count_bits(unsigned x) {
  int count = 0;
  while(x) {
    if(x & 1U) count++;
    x >>= 1;
  }
  return count;
}

int int_bits(void) {
  return count_bits(~0U);
}

void print_bits(unsigned x) {
  int i;
  for(i = int_bits() - 1; i >= 0; i--)
    putchar(((x >> i) & 1U) ? '1' : '0');
}

int main(void) {
  unsigned i;
  for(i = 0; i < UINT_MAX; i++) {
    print_bits(i);
    printf(" %6o %5u %4X\n", i, i, i);
  }
  return 0;
}