Convert binary string into decimal

懵懂的女人 提交于 2020-01-03 06:46:07

问题


I would like to convert a string that is a binary to a decimal.

Here is what the fullCard value is.

fullCard = "1000000100000101111101"

Here is what it should look like after being converted to decimal

fullCardInt = 2113917

Main.ino

String fullCard;                     // binary value full card number 

int fullCardInt = bin2dec(const_cast<char*>(fullCard.c_str()));  
// I get -1 which is a failure. 

serial.print(fullCardInt);

int bin2dec(const char *bin)
{
  int result=0;
  for(;*bin;bin++)
  {
    if((*bin!='0')&&(*bin!='1'))
      return -1;
    result=result*2+(*bin-'0');
    if(result<=0) return -1;
  }
  return result;
}

回答1:


1000000100000101111101 has 22 bits.

int on Arduino is 16-bit.

The solution is to use long (32-bit) instead of int.




回答2:


since this function is portable did you test it? did you instrument it to see what was going on? We are not here for code reviews nor to debug code.

#include <stdio.h>

int bin2dec(const char *bin)
{
  int result=0;
  for(;*bin;bin++)
  {
    if((*bin!='0')&&(*bin!='1'))
      return -1;
    result=result*2+(*bin-'0');
    if(result<=0) return -1;
  }
  return result;
}


int main ( void )
{
    printf("%d\n",bin2dec("1000000100000101111101"));
    return(0);
}

I get 2113917 as a result.

your code could use a couple of shortcuts but functionally it is sound. you didnt show us how you called it.

ahh yes, plus one gre_gor's answer that is the problem.

#include <stdio.h>

short bin2dec(const char *bin)
{
  short result=0;
  for(;*bin;bin++)
  {
    if((*bin!='0')&&(*bin!='1'))
      return -1;
    result=result*2+(*bin-'0');
    if(result<=0) return -1;
  }
  return result;
}


int main ( void )
{
    printf("%d\n",bin2dec("1000000100000101111101"));
    return(0);
}

results in -1 because you have this line in it

    if(result<=0) return -1;

which limits you to size of int - 1 bits. so 15 for a 16 bit int and 31 for a 32 bit.

#include <stdio.h>

short bin2dec(const char *bin)
{
  short result=0;
  for(;*bin;bin++)
  {
    if((*bin!='0')&&(*bin!='1'))
    {
        printf("here\n");
        return -1;
    }
    result=result*2+(*bin-'0');
    printf("0x%04X\n",result);
    if(result<=0)
    {
        printf("there\n");
        return -1;
    }
  }
  return result;
}


int main ( void )
{
    printf("%d\n",bin2dec("1000000100000101111101"));
    return(0);
}


0x0001
0x0002
0x0004
0x0008
0x0010
0x0020
0x0040
0x0081
0x0102
0x0204
0x0408
0x0810
0x1020
0x2041
0x4082
0xFFFF8105
there
-1

remember, plus one/accept gre_gor's answer not mine...



来源:https://stackoverflow.com/questions/48193700/convert-binary-string-into-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!