重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

電子書籍の厳選無料作品が豊富!

プログラムを始めてまだ二週間ぐらいの初心者なのですが、わけあって2進を10進に変換するのうを作ってこいといわれたのですがどうしたらいいのかわかりません^^;
だれか助けて~
あと自分はc++を使って書いています

A 回答 (3件)

おまけ


-------
#include <iostream>
#include <string>

using namespace std;

int btoi(string &binStr){
int ret=0;
for(size_t i=0;i<binStr.length();i++){
ret*=2;
if(binStr.at(i)=='1')
ret+=1;
}
return ret;
}

int main(void){
int d;
string binStr;

cout << "2進数を入力して下さい" << endl;
cin >> binStr;
d=btoi(binStr);
cout << d << endl;
return 0;
}
    • good
    • 0
この回答へのお礼

回答していただき本当にありがとうございます!

お礼日時:2005/07/31 09:11

2進文字列をコンソールから入力できるように変更してみました。


-------------------------------------------------------------
#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int main(void){
long int d;
string binStr;

cout << "2進数を入力して下さい" << endl;
cin >> binStr;
d=strtol(binStr.c_str(),NULL,2);
cout << d << endl;
return 0;
}
    • good
    • 0

#include <iostream>


#include <cstdlib>

int main(void){
long int d=strtol("10100101",NULL,2);
std::cout << d << std::endl;
}
    • good
    • 0
この回答へのお礼

お早い回答ありがとうございます
で、これをプログラムの中で自分の好きな数字を変換するにはどうしたらいいのでしょうか?
cinとintつかってやったらエラーがでてよくわかりません^^;

お礼日時:2005/07/30 19:32

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!