C++十进制与二进制的互相转换

手动实现进制转换

十进制转换为二进制:

1
2
3
4
5
6
7
8
9
10
11
12
int decTobin(int n)
{
int h,w=1,sum=0;
while (n)
{
h = n % 2;
sum += h * w;
w *= 10;
n = n / 2;
}
return sum;
}

二进制转换为十进制:

1
2
3
4
5
6
7
8
9
10
11
12
int binTodec(int n)
{
int h,w=1,sum=0;
while (n)
{
h = n % 10;
sum += h * w;
w *= 2;
n = n / 10;
}
return sum;
}
Author: wnxy
Link: https://wnxy.github.io/2020/02/10/C++_decimal-and-binary-conversion/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.