C ++位字符串到int转换 [英] C++ bit string to int conversion

查看:144
本文介绍了C ++位字符串到int转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将长度为'sLength'的位串(bitString)转换为int。
以下代码在我的计算机上适用于我。是否有可能无法正常工作?

  int toInt(string bitString,int sLength){

int tempInt;
int num = 0;
for(int i = 0; i tempInt = bitString [i] - '0';
num = num + tempInt * pow(2,(sLength-1-i));
}

return num;先感谢提前

h2_lin>解决方案

pow 适用于双打。结果可能不准确。使用位算法

  num | =(1 <<<(sLength-1-i))* tempInt; 

不要忘记 bitString 包含除0和1之外的符号或太长


I am trying to convert a bit string (bitString) of length 'sLength' to an int. The following code works fine for me in my computer. Is there any case where it may not work?

int toInt(string bitString, int sLength){

    int tempInt;
    int num=0;
    for(int i=0; i<sLength; i++){
        tempInt=bitString[i]-'0';
        num=num+tempInt * pow(2,(sLength-1-i));
    }

    return num;
}

Thanks in advance

解决方案

pow works with doubles. Result may be inaccurate. Use bit arithmetic instead

num |= (1 << (sLength-1-i)) * tempInt;

Don't also forget about cases when bitString contains symbols other than '0' and '1' or too long

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

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