Reputation: 1721
I want to convert 64 bit binary string to 64 bit integer (unsigned). Is there any library function to do that in C++ ?
Edit:
I use:
main()
{
std::string st = "010111000010010011000100010001110110011010110001010111010010010110100101011001010110010101101010" ;
uint64_t number;
number = strtoull (st.c_str (),NULL,2);
cout << number << " " ;
char ch = std::cin.get();
cout << ch ;
return 0;
}
Upvotes: 6
Views: 40661
Reputation: 631
Converts binary string to integer and binary string (up to 64 bits) to long. Uses bit-shifting so slightly more efficient than pow().
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
string getBinaryString(int value, unsigned int length, bool reverse) {
string output = string(length, '0');
if (!reverse) {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << i)) != 0) {
output[i] = '1';
}
}
}
else {
for (unsigned int i = 0; i < length; i++) {
if ((value & (1 << (length - i - 1))) != 0) {
output[i] = '1';
}
}
}
return output;
}
unsigned long getInteger(const string& input, size_t lsbindex, size_t msbindex) {
unsigned long val = 0;
unsigned int offset = 0;
if (lsbindex > msbindex) {
size_t length = lsbindex - msbindex;
for (size_t i = msbindex; i <= lsbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << (length - offset));
}
}
}
else { //lsbindex < msbindex
for (size_t i = lsbindex; i <= msbindex; i++, offset++) {
if (input[i] == '1') {
val |= (1 << offset);
}
}
}
return val;
}
int main() {
int value = 23;
cout << value << ": " << getBinaryString(value, 5, false) << endl;
string str = "01011";
cout << str << ": " << getInteger(str, 1, 3) << endl;
}
Upvotes: 0
Reputation: 11
The following code is probably the simplest way to convert binary string to its integer value. Without using biteset or boost this works for any length of binary string.
std::string binaryString = "10101010";
int value = 0;
int indexCounter = 0;
for(int i=binaryString.length()-1;i>=0;i--){
if(binaryString[i]=='1'){
value += pow(2, indexCounter);
}
indexCounter++;
}
Upvotes: 1
Reputation: 55887
If you have C++11 - you can use std::bitset
for example.
#include <iostream>
#include <bitset>
int main()
{
const std::string s = "0010111100011100011";
unsigned long long value = std::bitset<64>(s).to_ullong();
std::cout << value << std::endl;
}
or std::stoull
#include <iostream>
#include <string>
int main()
{
const std::string s = "0010111100011100011";
unsigned long long value = std::stoull(s, 0, 2);
std::cout << value << std::endl;
}
Upvotes: 11
Reputation:
You may try this. If you don't need it to be generic, you can specify the type and do away with Number:
template <typename Number>
Number process_data( const std::string& binary )
{
const Number * data_ptr;
Number data;
data_ptr = reinterpret_cast<const Number*>(binary.data());
data = *data_ptr;
return data;
}
Upvotes: -1
Reputation: 136256
You can use strtoull()
function with base 2 (there is an example if you follow the link).
Upvotes: 12