Hello ...

I've been trying to convert a long string of numbers into a number that can be used in calculations ( int, long, or long long ) ... but nothing worked :-|

If I have a string of 1s and 0s, and this string could be up to 128 characters in length, how can I convert it into a binary number, or any format as long as I can use it to perform calculations on it ?

Thanks in advance ^-^

Recommended Answers

All 5 Replies

Use istringstream

Realize that if you have 128 binary digits, you won't be able to store that in a long or long long datatype.

I have to get two strings of an unknown length, that could be up to 128 bits long, the problem is I need to convert them into numbers, I know that the data types available are not big enough to store such a number.

I need to convert these strings in order to be able to use division, to find the Cyclic Redundancy Check (CRC), I am not sure if I am approaching the problem in the right way ...

One concept that works no matter what base you are using to do the math is to realize that you don't do the arithmetical operation on the whole string/number at once, rather you do the arithmetical operation on(one or) two ints at a time. So you somehow need to change a char into an int and then do the math. When the math is done you need to change a single digit back into the appropriate char and do something with carry over (or borrowing) as the case may be. Alternatively you might be able to do bit shifting, etc., if you make appropriate conversions, have enough experience manipulating bits, etc.

To convert char to ints you can use any number of strategies including stringstreams, atoi, strtol, or subtract the the ASCI value of zero from any other given char (which takes advantage of the fact that most routine char sets have the digits in chronological order ranging from 0-9).

To convert an int back to a char you can likewise use a stringstream, sprintf, add the value of the int to the character value of zero, or use the non standard itoa, if you have the necessary header file available.

You can try and use look-up-table and bit-shifting to implement it. It's fairly easy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.