Frage

I have seen lots of ways to convert a string such as "12345" into an integer based on what the charecters represent ( the integer 12345 ) , but I need to be able to take a string's binary equivalent and turn that into an integer. For example , take the string "Hello!" . On the hard drive ( or memory ) it is stored as a binary pattern :

010010000110010101101100011011000110111100100001

If you treat these bits as a binary number instead of text, then that pattern is also equal to 79600447942433.

"Hello!" = 79600447942433

The only way I now of is to loop until the end of a string and convert individual charecters into integers, then multiply by 2^ position_of_charecter

#include <string>
#include <cmath>
using namespace std ;
// ...
string str = "Hello!" ; int i , total , temp ; unsigned char letter ;
for ( i = 0 ; i < str.length() ; i++ )
{
    letter = string[ i ] ;
    temp = ( int ) letter ;
    total += ( temp * pow( 2 , i ) ) ;
}
cout << "\"Hello!\" is equal to " << total << endl ;

But I am working with very large strings and would like a faster way to convert it

War es hilfreich?

Lösung 2

You can use the std::bitset<> class. See sample below.

#include <bitset>
#include <iostream>

using namespace std;

int main()
{
    bitset<64> allBits("010010000110010101101100011011000110111100100001");
    cout << allBits.to_ullong();  // C++ 11.  If using earlier version, use to_ulong().
}

Note that the integer will need to fit within the maximum limit of an unsigned long if to_ulong() is used, and an unsigned long long if to_ullong() is used.

Andere Tipps

First improvement: Replace pow and the associated conversions with a left shift (<<).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top