If I have a string "52" is there a way to convert this to it's two's complement value(in bits), which is 00110100 WITHOUT converting 52 to an int first...
I would like to store this two's complement number into an array, so the final result would be:
a = {0, 0, 1, 1, 0, 1, 0, 0};
reason I asked without converting it first is because I want to convert:
You could use a library made to handle arbitrary precision integers. I think one is called BigInt or BigNum or something like that, go try google and see what you get.
It is possible to do this without a big math library. I have code to do arbitrary base
conversions (bases 2-62, limited only by reasonable printable character set) that
I wrote 11 years ago, however I cannot post it here.
The general gist of the solution is to perform long-hand division. In long-hand division,
you only ever have to look at a few digits at a time... well within the 32-bit unsigned
limit.
my purpose here is to write my own bignum class.... my constructor needs to take a string and I want to convert this string to a two's complement and store the bits in a vector
The general gist of the solution is to perform long-hand division. In long-hand division, you only ever have to look at a few digits at a time... well within the 32-bit unsigned
limit.
I must be dense... but how do you use long division to convert base 10 to base 2?
I thought about doing a "digit at a time" approach at first too, but my first thought was foiled when I realized the right-most digit of the base 10 number can impact the left-most digit of the base 2 number.
I suppose if you go through every digit and add carry to them... but isn't like like making a miniature bignum lib?
I think if some can show a code example to do this via long division that would make a lot of sense as it doesn't make quite much sense to me right now....
Also, having n bits:
Lowest negative number: -2^(n-1), in binary, 1 followed by n-1 zeroes
-1: n ones
EDIT: All you do is take the string and treat it as a decimal representation of a value. "52" is 5*10+2. The rest is just iterated division by 2 on this array. The main part of the problem is writing the division mechanism. Just use the algorithm you were taught in elementary school.
EDIT 2: I should mention that what you really use is the remainders, not the quotients, to build the binary representation.