[c][cpp]: decimal to binary
一、源码
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 6 // decial to binary; 10 -> 2 7 void dec2bin(long int num) 8 { 9 int final[1000]; 10 11 long int save_num = num; 12 13 // calculate 14 int count = 0; 15 while ( num > 0 ) 16 { 17 final[ count ] = num % 2 ; 18 num /= 2 ; 19 count++ ; 20 } 21 22 // output 23 printf ( "\n dec2bin(decimal %ld) := ", save_num); 24 25 while ( count >= 0 ) 26 { 27 printf("%d", final[ count-- ] ); 28 } 29 printf("\n"); 30 } 31 32 33 void run() 34 { 35 dec2bin(0); 36 dec2bin(1); 37 dec2bin(2); 38 dec2bin(8); 39 dec2bin(1024); 40 dec2bin(65536); 41 } 42 43 44 int main() 45 { 46 run(); 47 return 0; 48 }
二、运行
1 g++ -std=c++20 -O2 -Wall main.cpp && ./a.out 2 3 4 dec2bin(decimal 0) := 0 5 6 dec2bin(decimal 1) := 01 7 8 dec2bin(decimal 2) := 010 9 10 dec2bin(decimal 8) := 01000 11 12 dec2bin(decimal 1024) := 010000000000 13 14 dec2bin(decimal 65536) := 010000000000000000
三、参考文献
1、 数字转二进制(4种方法) | 位域(位段)应用 —— 从内存中提取数字的二进制 -- https://blog.csdn.net/weixin_43919932/article/details/121854411
标签:count,binary,int,decimal,dec2bin,num,cpp From: https://www.cnblogs.com/lnlidawei/p/17972504