gpt4 book ai didi

flutter - 如何在dart中将二进制数转换为小数?

转载 作者:行者123 更新时间:2023-12-03 03:05:13 24 4
gpt4 key购买 nike

嗨,我一直想知道是否有一种方法可以将二进制数转换为十进制分数。

我知道如何通过此代码更改基数作为示例

String binary = "11110010";

//I'd like to change this line so it produces a decimal value
String denary = int.parse(binary, radix: 2).toRadixString(10);

最佳答案

int binaryToDecimal(int n)
{
int num = n;
int dec_value = 0;

// Initializing base value to 1, i.e 2^0
int base = 1;

int temp = num;
while (temp) {
int last_digit = temp % 10;
temp = temp / 10;

dec_value += last_digit * base;

base = base * 2;
}
return dec_value;
}

int main()
{
int num = 10101001;
cout << binaryToDecimal(num) << endl;
}
这是我的c++解决方案,但是您可以实现任何语言

关于flutter - 如何在dart中将二进制数转换为小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976577/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com