为了将二进制转换为十进制,这里我使用了 while 循环并找到了二进制数的余数,即输入。之后,将余数乘以基值并相加。
这就是我获得十进制值的方法 -
while (val > 0) { remainder = val % 10; mydecimal = mydecimal + remainder* baseval; val = val / 10; baseval = baseval * 2;}
示例让我们看看在 c# 中将二进制转换为十进制的完整代码 -
现场演示
using system;using system.collections.generic;using system.text;namespace demo { class tobinary { static void main(string[] args) { int val = 1010, mybinary, remainder; int mydecimal = 0, baseval = 1; mybinary = val; while (val > 0) { remainder = val % 10; mydecimal = mydecimal + remainder * baseval; val = val / 10; baseval = baseval * 2; } console.write("binary number : " + mybinary); console.write("converted to decimal: " + mydecimal); console.readline(); } }}
输出binary number : 1010converted to decimal: 10
以上就是使用 c# 进行二进制转十进制的详细内容。