c++ - Convert string to integer ( binary equivalent ) -
i have seen lots of ways convert string such "12345" integer based on charecters represent ( integer 12345 ) , need able take string's binary equivalent , turn that integer. example , take string "hello!" . on hard drive ( or memory ) stored binary pattern :
010010000110010101101100011011000110111100100001
if treat these bits binary number instead of text, pattern equal 79600447942433.
"hello!" = 79600447942433
the way of loop until end of string , convert individual charecters integers, multiply 2^ position_of_charecter
#include <string> #include <cmath> using namespace std ; // ... string str = "hello!" ; int , total , temp ; unsigned char letter ; ( = 0 ; < str.length() ; i++ ) { letter = string[ ] ; temp = ( int ) letter ; total += ( temp * pow( 2 , ) ) ; } cout << "\"hello!\" equal " << total << endl ;
but working large strings , faster way convert it
you can use 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 integer need fit within maximum limit of unsigned long if to_ulong() used, , unsigned long long if to_ullong() used.
Comments
Post a Comment