ord*_*ary 1 c++ binary decimal
while(i < length)
{
pow = 1;
for(int j = 0; j < 8; j++, pow *=2)
{
ch += (str[j] - 48) * pow;
}
str = str.substr(8);
i+=8;
cout << ch;
ch = 0;
}
Run Code Online (Sandbox Code Playgroud)
这似乎减慢了我的计划.是因为我在那里使用的字符串函数,或者这种方法通常是错误的.我知道有实现长除法的方法,但我想知道这是否实际上比这种方法更有效.我想不出另一种不使用相同通用算法的方法,所以也许只是我的实现就是问题.
也许你想要考虑使用标准库函数.它们可能至少与您通过编译器运行的任何内容一样优化:
#include <iostream>
#include <iomanip>
#include <cstdlib>
int main (void) {
const char *str = "10100101";
// Use str.c_str() if it's a real C++ string.
long int li = std::strtol (str, 0, 2);
std::cout
<< "binary string = " << str
<< ", decimal = " << li
<< ", hex = " << std::setbase (16) << li
<< '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
binary string = 10100101, decimal = 165, hex = a5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
232 次 |
| 最近记录: |