Delali Dzirasa said:
Does anyone know of the fastest way to convert a CString of numbers ie
"00000001" to the binary representation in an int?
There's no 'CString' type in standard C++. I can show you
how to convert a 'std::string' containing text representing
a binary value to an integer type.
You'll need to figure out how to convert from 'CString'
to 'std::string'. This is indeed possible, look up
the 'CString' and 'std::string' member functions.
Also, since there's no way to determine the which binary
representation an implementation uses, it doesn't really make sense
to try to represent the binary pattern of a signed type
like that. So my example below uses an unsigned int instead
of signed.
for example
CString myVal = "00000001";
int myIntVal = 0;
myIntVal = CStringToBinary(myVal);
where the "CStringToBinary" function is what I am looking to find.
the int representation should be 1 or in hex 0x01
Any help is greatly appreciated.
#include <bitset>
#include <climits>
#include <iostream>
#include <stdexcept>
#include <string>
unsigned int binstr2uint(const std::string& s)
{
const std::string::size_type
max_bits(sizeof(unsigned int) * CHAR_BIT);
if(s.size() > max_bits)
throw "[binstr2uint]: Too many digits in input\n";
return (std::bitset<max_bits>(s).to_ulong());
}
int main()
{
std::string s("101010101");
try
{
unsigned int i(binstr2uint(s));
std::cout << "s == " << s << '\n'
<< "i == " << i << '\n';
}
catch(const char *e)
{
std::cout << e << '\n';
}
catch(std::invalid_argument&)
{
std::cout << "[binstr2uint]: Invalid digit in input\n";
}
return 0;
}
Output:
s == 101010101
i == 341
-Mike