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;
}
1000000100000101111101
has 22 bits.
int
on Arduino is 16-bit.
The solution is to use long
(32-bit) instead of int
.
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...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.