[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
本文由 lnlidawei 原创、整理、转载,本文来自于【博客园】; 整理和转载的文章的版权归属于【原创作者】; 转载或引用时请【保留文章的来源信息】:https://www.cnblogs.com/lnlidawei/p/17972504