Reputation: 71
I would like to have a data type that stores a binary number that is 21 digits long that I can do operations on. I tried
unsigned long long int
and it was just barely to small. This is wasting a lot of space bc my number is binary an the computer is storing it a a integer so the question is is there a type that stores it as a binary number but I can still do like modular operations on it.
I read a few related posts and did not think they quite addressed my question. If there is one I missed I would appreciate some one pointing me there thanks.
Update so hear is a snipit of the code that is the problem
It is crashing after
unsigned long long int a;
cin>>a;
Which in tern must go to
void convertNumtoArray(unsigned long long int a, x & binaryA){
int j=0;
while(a!=0){
unsigned long long int remainder=a % 10;
a=a/10;
binaryA.a[j]=remainder;
binaryA.length_a=j+1;
j++;
}
}
Upvotes: 1
Views: 19223
Reputation: 263627
unsigned long long int remainder=a % 10;
a=a/10;
You're dividing by ten, which means you're treating the value as a decimal number. (The constant 10
is decimal, not binary.) 21 decimal digits are equivalent to approximately 70 bits, which is why unsigned long long int
(typically 64 bits) is not wide enough.
Change 10
to 2
. (I haven't checked for other problems in your code, but that's a start.)
(You might also consider using bitwise operators, but division by 2
should work and might be easier to understand for now.)
Upvotes: 1
Reputation: 6467
I would like to have a data type that stores a binary number that is 21 digits long that I can do operations on.
One way to tackle this is by using bitset
, here is an example of constructing and using of such object:
#include <iostream>
#include <string>
#include <bitset>
int main ()
{
std::bitset<16> foo;
std::bitset<16> bar (0xfa2);
std::bitset<16> baz (std::string("0101111001"));
std::cout << "foo: " << foo << '\n';
std::cout << "bar: " << bar << '\n';
std::cout << "baz: " << baz << '\n';
}
The above prints:
foo: 0000000000000000
bar: 0000111110100010
baz: 0000000101111001
This gives you direct access over the size of the variable you want to define (in your case 21 bits?), in bits, as well as possibility for binary operations.
Upvotes: 7