lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

[c][cpp]:  decimal to binary

 

 

 

 

一、源码

 1 #include <stdio.h>
 2 
 3 
 4 // decimal to binary;    10 -> 2
 5 void dec2bin(long int num)
 6 {
 7     int res[1000];
 8 
 9     long int save_num = num;
10 
11     // calculate
12     int count = 0;
13     while ( num > 0 )
14     {
15         res[ count++ ] = num % 2 ;
16         num /= 2 ;
17     }
18 
19     // output
20     printf ( "\n dec2bin(decimal %ld) := ", save_num);
21     while ( count >= 0 )
22     {
23         printf("%d", res[ count-- ] );
24     }
25     printf("\n");
26 }
27 
28 
29 void run()
30 {
31     dec2bin(0);
32     dec2bin(1);
33     dec2bin(2);
34     dec2bin(8);
35     dec2bin(1024);
36     dec2bin(65536);
37 }
38 
39 
40 int main()
41 {
42     run();
43     return 0;
44 }

 

 

 

二、运行

 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

 

posted on 2024-01-18 14:48  lnlidawei  阅读(9)  评论(0编辑  收藏  举报