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 ?

4
Contributors
5
Replies
7
Views
11 Years
Discussion Span
Last Post by Grunt

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.