012
02.03.2008, 18:43 Uhr
Kest
saint
|
Hi!
Wenn in C++ und ein wenig Mathe:
C++: |
#include <string> #include <bitset> #include <stdexcept> #include <iostream> #include <cmath>
unsigned long long to_u_long_long(const std::string& str){ const int ULL = sizeof(unsigned long long) * 8; const int UL = sizeof(unsigned long) * 8;
if(str.length()<=UL) return std::bitset<UL>(str).to_ulong();
return std::bitset<UL>(str, str.length()-UL).to_ulong() + ( std::bitset<UL>(str, 0, str.length()-UL).to_ulong() * static_cast<unsigned long long>(std::pow(static_cast<double>(2), UL)) ); }
std::string to_binaer(unsigned long long zahl){ std::string _t; for(int i=sizeof(unsigned long long)*8-1; i>=0; i--) _t.push_back( ((zahl>>i)&1)+'0' );
return _t; }
int main() { std::string s; while(true){ std::getline(std::cin, s);
if(s.length()>sizeof(unsigned long long)*8 || s==""){ std::cout << "falsche Eingabe" << std::endl; continue; }
try{ std::bitset<sizeof(unsigned long long)*8> bs(s); }catch(std::invalid_argument){ std::cout << "keine gültige Binärzahl" << std::endl; continue; }
break; }
unsigned long long l = to_u_long_long(s); std::cout << l << std::endl; std::cout << to_binaer(l); }
|
-- Wenn man einen Hufschlag hört, sollte man >Pferd< denken und nicht >Zebra<. |