简体   繁体   English

将二进制向量转换为十进制数组

[英]Converting a binary vector into a decimal array

I've created a method to generate random binary numbers with n-digits up to 256 digits. 我创建了一种方法来生成n位数字(最多256位)的随机二进制数。 In order to continue with my program I need to take the vector with my binary value and put it into a decimal array and then convert that number into a int decimal. 为了继续我的节目,我需要采取的载体与我的二进制值,并把它变成一个小数数组,然后转换这个数字为int小数。 Here's the following function that creates the random binary vector and my attempt to convert to decimal. 以下是创建随机二进制向量的以下函数,以及我尝试转换为十进制的尝试。 I'm having trouble converting my binary vector to a decimal. 我在将二进制矢量转换为十进制时遇到麻烦。

int random_binary(int n, int m){

   vector<int> binary;

   for(int i = 0; i < n; i++)
   {
      m = rand() % 2;

      binary.push_back(m);
   }

   binary.push_back(1);

   int j;

   for(j = 0; j < binary.size(); j++)
   {
       cout << binary[j];
   }
   cout <<"\n";


   int len = binary.size();
   int a = binary[len];   //having trouble right here

   int decimalValue = 0;

   for (int i = len-1; i>= 0; i--)
   {
       decimalValue = decimalValue + binary[i]*pow(2,len-i-1);
   }

   return decimalValue;
}

If anybody could help figure this out that would be much appreciated. 如果有人可以帮助解决这个问题,将不胜感激。

The code isn't all that bad, but it does have a few problems: 代码并不是很糟糕,但是确实存在一些问题:

  • An int value can only hold 32 bits on most platforms, 31 bits if you only want non-negative values. 在大多数平台上, int值只能容纳32位,如果只希望使用非负值,则可以容纳31位。 So for 256 binary digits, you will need to use something else. 因此,对于256个二进制数字,您将需要使用其他内容。

  • int a = binary[len]; //having trouble right here int a = binary[len]; //having trouble right here - I think @PaulMcKenzie interprets this as an attempt to declare an array of int with a variable number of elements ( int a[len]; ). int a = binary[len]; //having trouble right here -我认为@PaulMcKenzie将此解释为试图声明具有可变数量元素( int a[len]; )的int数组。 I see it as probably initializing an int variable to the element in binary one past the last entry. 我认为它可能是在最后一项之后的binary初始化了一个int变量给该元素。 Either way is wrong -- but you never use a anyway, and I don't see any possible use for it. 无论哪种方式是错的-但你从来没有使用a反正,和我没有看到它的任何可能的用途。 So just delete that line. 因此,只需删除该行。

  • Not a bug, but you should understand that int decimalValue isn't decimal, it is an integer, which is most likely stored inside the computer as a set of bits, and only appears as a decimal number when converted and displayed a certain way, like when printed using std::cout . 这不是错误,但您应该理解int decimalValue不是十进制,它是一个整数,很可能以一组位的形式存储在计算机中,并且仅在以某种方式转换和显示时才显示为十进制数,就像使用std::cout打印时一样。

  • In the sum loop, std::pow should not be used for integer values, but luckily the bit left shift operator can be used to get integer powers of 2: 在求和循环中,不应将std::pow用于整数值,但幸运的是,可以使用左移运算符获得2的整数次幂:
    decimalValue = decimalValue + binary[i] * (1<<(len-i-1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM