C言語 整数型の変数を2進数で表示するプログラム
整数型(char, short, int, long, __int64(Windows環境))を2進数で表示するプログラム
#include <stdio.h> #include <limits.h> #define INT64_BIT 64 #define LONG_BIT 32 #define INT_BIT 32 #define SHRT_BIT 16 void print_binary_int64(__int64 n) { for (long i = INT64_BIT-1; i >= 0; i--) { putchar(n & ( __int64(1) << __int64(i) ) ? '1' : '0'); } putchar('\n'); } void print_binary_long(long n) { for (long i = LONG_BIT-1; i >= 0; i--) { putchar(n & (1 << i) ? '1' : '0'); } putchar('\n'); } void print_binary_int(int n) { for (int i = INT_BIT-1; i >= 0; i--) { putchar(n & (1 << i) ? '1' : '0'); } putchar('\n'); } void print_binary_short(short n) { for (short i = SHRT_BIT-1; i >= 0; i--) { putchar(n & 1 << i ? '1' : '0'); } putchar('\n'); } void print_binary_char(char n) { for (char i = CHAR_BIT-1; i >= 0; i--) { putchar(n & 1 << i ? '1' : '0'); } putchar('\n'); } int main() { printf("char: "); print_binary_char(10); printf("short: "); print_binary_short(short(10)); printf("int: "); print_binary_int(10); printf("long: "); print_binary_long(10L); printf("__int64: "); print_binary_int64(__int64(10)); return 0; }
char: 00001010 short: 0000000000001010 int: 00000000000000000000000000001010 long: 00000000000000000000000000001010 __int64: 0000000000000000000000000000000000000000000000000000000000001010
int型の整数であれば、itoa関数が使える。
#include <stdio.h> #include <stdlib.h> int main() { char buff[16] = {'\0'}; itoa(10, buff, 2); puts(buff); return 0; }