将二进制字符串转换为十进制 [英] Convert binary string into decimal

查看:285
本文介绍了将二进制字符串转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将二进制的字符串转换为十进制.

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

这是fullCard的值.

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具有22位.

int是16位的.

解决方案是使用long(32位)代替int.

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

这篇关于将二进制字符串转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆