Created
February 14, 2011 08:11
-
-
Save mumumu/825602 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What happens if num is a negative integer?