Skip to content

Instantly share code, notes, and snippets.

@mumumu
Created February 14, 2011 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mumumu/825602 to your computer and use it in GitHub Desktop.
Save mumumu/825602 to your computer and use it in GitHub Desktop.
#include <stdio.h>
/*
* int を2進表記にして出力する
* int を 32bit と仮定している
*/
int binary(int num)
{
//
// - 以下のルーチンでint の範囲に収まる値は扱うことができるが
// 二つの欠点がある
//
// 1. ビットシフト演算子は汎整数型しかオペランドにとれないこ
// とから、double や float はこの方法では扱えない。
//
// doubleやfloatを扱いたいのであれば、C言語では共用体を
// 使うなり、char * にキャストするなりして無理矢理整数型
// として値を覗くしかない。但し、他の言語ではこのような方法
// をとれるとは限らない。
//
// @see
// http://www.asahi-net.or.jp/~uc3k-ymd/Lesson/Section01/section01_06.html
//
// 2. ビットシフト演算子は左オペランドのサイズ以上の値を右オペ
// ランドに指定すると結果が未定義であることから、整数型の
// サイズ以上の値を扱えない。これは、多倍長整数をどう扱う
// かという話題に繋がるので、いったんここでは置いておく。
//
int i;
for (i = 31; i >= 0; i--) {
printf("%d", (num >> i) & 1);
}
printf("\n");
}
int main(int argc, char *argv[])
{
int num = 0;
scanf("%d", &num);
binary(num);
}
@pascaljp
Copy link

What happens if num is a negative integer?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment