将二进制转换为十进制在C中使用数组

huangapple go评论58阅读模式
英文:

converting binary to decimal in c using arrays

问题

我试图将一个二进制数转换为十进制。在我的代码中,将把数字输入为整数数组的成员,然后对每个成员执行一些数学运算,最后将结果添加并存储在另一个变量中。最初,我希望将二进制数作为字符串收集,然后使用atoi或strol将其转换为整数数组,但我无法实现,所以我尝试了这种方法。

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int binToint(int arrName[]);

int binToint(int arrName[]) {
  int index;
  int length, j, x = 0; //初始化长度、x和j为0

  for (index = 0; arrName[index] == 1 || arrName[index] == 0; index++)
    ++length;
  j = length;

  for (index = 0; index < length; index++) {
    --j;
    if (j < 0)
      break;

    x += arrName[index] * ((int)pow(10, j)); //十进制 = 二进制 x 10^位数的指数
  }
  printf("结果:%d", x);
  return x;
}

int main(void) {

  int tester[] = {1, 1, 1, 0, 1, 1}; //我使用逗号以便每个数字都可以单独存储
  binToint(tester); //调用函数
}

运行后,我没有得到任何输出,而是得到一个空屏幕。

输出应该是:

结果:59

如果能找到并纠正我的错误,我将不胜感激。我也将感激对我的代码进行优化。谢谢!

英文:

I'm trying to convert a binary number to a decimal. In my code, the digits will be inputed as members of an array of integers, then some mathematical operations will be done on each member and finally adding and string the result in another variable. I initially wanted collecting my binary number as a string then converting to an array of int using atoi or strol but I couldn't so I tried this way.

#include &lt;math.h&gt;
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int binToint(int arrName[]);

int binToint(int arrName[]) {
  int index;
  int length, j, x = 0; //initializing length, x and j to 0

  for (index = 0; arrName[index] == 1 || arrName[index] == 0; index++)
    ++length;
  j = length;

  for (index = 0; index &lt; length; index++) {
    --j;
    if (j &lt; 0)
      break;

    x += arrName[index] * ((int)pow(10, j)); //decimal = binary x 10^index of digit
  }
  printf(&quot;Result: %d&quot;, x);
  return x;
}

int main(void) {

  int tester[] = {1,1,1,0,1,1}; //i used the commas so that each digit will be stored separately
  binToint(tester); //calling the function
}

After running, I didn't get any output, rather, I got an empty screen.
The output is supposed to be:

 Result: 59

I will be glad if my mistakes are spotted and corrected. I will also appreciate optimizations to my code. Thanks

答案1

得分: 1

不翻译代码部分。以下是翻译好的内容:

Remember that any number is just the coefficients of a polynomial for each power of the radix (or base). That is:

For binary the radix is not 10, but 2. So:

The neat trick is that all this “power of” stuff is just repeated multiplication, so it is very easy to build a number up by just starting with the leftmost (most-significant) digit, and then multiplying by the radix each time before adding the next digit value:

When you are given an array of binary values (0 or 1, not '0' or '1') you can easily build up your result. Start with 0 and simply multiply and add for each next digit:

Going backwards (int to array) is only complicated by the fact that you can only peel digits off from the right (least-significant), but is otherwise just as simple.

Good luck!

英文:

Remember that any number is just the coefficients of a polynomial for each power of the radix (or base). That is:

<b></b>      3×10<sup>2</sup>  +  0×10<sup>1</sup>  +  7×10<sup>0</sup>    ==     3 0 7    ==     307

For binary the radix is not 10, but 2. So:

<b></b>      1 0 1 1<sub>2</sub>    ==     1×2<sup>3</sup> + 0×2<sup>2</sup> + 1×2<sup>1</sup> + 1×2<sup>0</sup><br>      ⟶     8 + 0 + 2 + 1    ==     11<sub>10</sub>

The neat trick is that all this “power of” stuff is just repeated multiplication, so it is very easy to build a number up by just starting with the leftmost (most-significant) digit, and then multiplying by the radix each time before adding the next digit value:

multiply,    add
0 * 2 =  0,  0 + [1] (first digit)  = 1
1 * 2 =  2,  2 + [0] (second digit) = 2
2 * 2 =  4,  4 + [1] (third digit)  = 5
5 * 2 = 10, 10 + [1] (fourth digit) = 11 (final answer)

When you are given an array of binary values (0 or 1, <s>not &#39;0&#39; or &#39;1&#39;</s>) you can easily build up your result. Start with 0 and simply multiply and add for each next digit:

int value = 0;
for (each digit in the input array, left to right)
{
  value *= 2;
  value += digit;
}
return value;

Going backwards (int to array) is only complicated by the fact that you can only peel digits off from the right (least-significant), but is otherwise just as simple.

Good luck!

答案2

得分: 1

代码风险越过数组的末尾。

使用:

int tester[] = {1,1,1,0,1,1};
binToint(tester);

int binToint(int arrName[])

for (index = 0; arrName[index] == 1 || arrName[index] == 0; index++)

没有确保 arrName[index] 不会超过 arrName[5]

代码应该传入一个 长度

int tester[] = {1,1,1,0,1,1};
int n = sizeof tester/sizeof tester[0];
binToint(n, tester);

然后进行迭代:

int binToint(int n, int arrName[]) {
  ...
  for (index = 0; index < n; index++)

错误的初始化

只有 x 被初始化。

// int length, j, x = 0;
int length = 0;
int j = 0;
int x = 0;

没有溢出检测

健壮的代码应该在尝试形成超过 INT_MAX 的值时发出警告。

代码可能还有其他问题

英文:

Code risks running off the end of the array.

With

int tester[] = {1,1,1,0,1,1};
binToint(tester);

And with int binToint(int arrName[])

for (index = 0; arrName[index] == 1 || arrName[index] == 0; index++)

nothing is to certainly stop arrName[index] from going past arrName[5].

Code should pass in a length.

int tester[] = {1,1,1,0,1,1};
int n = sizeof tester/sizeof tester[0];
binToint(n, tester);

And then iterate:

int binToint(int n, int arrName[]) {
  ...
  for (index = 0; index &lt; n; index++)

Bad initialization

Only x in initialized.

// int length, j, x = 0;
int length = 0;
int j = 0;
int x = 0;

No overflow detection

Robust code would complain about trying to form a value more than INT_MAX.

Code may have other issues too

答案3

得分: 1

正如其他人所说,你无法在函数内部计算数组的长度。长度必须作为参数传递给函数。

我添加了一个新参数,len

在那之后,使用位移运算来计算值就非常简单了。

#include <stdio.h>

int binToint(int bits[const], int len)
{
	int answer = 0;
	for(int i=0; i<len; ++i)
	{
		answer = (answer << 1) + bits[i];
	}
	return answer;
}

int main(void) {

  int tester[] = {1,1,1,0,1,1};
  int result = binToint(tester, 6); //调用函数时,包括长度参数。
  
  printf("Result is %d\n", result);
}

输出

Result is 59
英文:

As others have said, you cannot calculate the length of an array from inside a function. The length must be passed to the function.

I added a new parameter, len.

After that, calculating the value with bit-shifting is trivially easy.

#include &lt;stdio.h&gt;

int binToint(int bits[const], int len)
{
	int answer = 0;
	for(int i=0; i&lt;len; ++i)
	{
		answer = (answer &lt;&lt; 1) + bits[i];
	}
	return answer;
}

int main(void) {

  int tester[] = {1,1,1,0,1,1};
  int result = binToint(tester, 6); //calling the function, including the length.
  
  printf(&quot;Result is %d\n&quot;, result);
}

Output

Result is 59

huangapple
  • 本文由 发表于 2023年2月8日 20:41:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定