I would advise against using an integer to store an apparent binary representation of a number. For one thing, the number of digits available is very limited, for another, it can be very confusing, as the value looks like an ordinary integer, but you won't be able to do any of the typical arithmetic operations using that value.
A string would be better. But really it depends what it is you are attempting to achieve.
This concept is from my subnet calculator (posted in articles.) Using bitwise operators you can make short work of the problem. Assign the customary 128 bits to a variable to indicate the binary mask and use the bitwise AND and SHIFT operators, Try this:
When we convert between bases by hand, using a pencil and paper, it is very convenient to convert from binary to either octal or hexadecimal, simply by considering groups of three or four bits at a time.
But when using a computer, rather than being simpler that way, it would just generate extra work and complexity. I'd suggest just convert direct from a plain int directly to whichever base is required.
this is my method of converting small binary numbers to decimals:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int x, t=0, digit, binary;
vector<int> digitstack;
cin >> x;
while(x>0)
{
digit = x % 10;
x = x / 10;
digitstack.push_back(digit);
}
while(t!=digitstack.size())
{
binary=binary + digitstack[t] * pow((double)2 , (double)t); t++;
}
cout << binary;
What do you think? Also, using same method you can convert from decimal to binary: you push 1's and 0's to the container and then just multiply them by 10^t.
Also sorry, binary should be named x here and x should be named binary.
but I didn't understand what did you do in the function,,, and i have to explain how i wrote my code to the teacher. So i need to write it in simple way :)
Chervil,,,
How can i use string to save the values ?