Code for converting binary number to decimal number - c++

I have some code that I wrote up that will successfully return me a binary number. For example, running the code below with an input of 101 will return 5. However, the problem arises when I add 0 bits to the left of MSB, thus not changing the value. When I input 0101 into the system, I should expect 5 to be returned again, but it returns 17 instead.
Here is my code:
int dec1 = 0, rem1=0, num1, base1 = 1;
int a = 101;
while (a > 0){
rem1 = a % 10;
dec1 = dec1 + (rem1 * base1);
base1 = base1 * 2;
a = a / 10;
}
cout << dec1 << endl;
The output of this is 5. Correct.
However, when 'a' is changed to 0101, the output becomes 17. I believe my error has to do with a misunderstanding of the modulo operator.
101%10 = 1 right? Does the compiler typically read 0101%10 the same way?
I added a cout statement to my code to see what value is stored in rem1 after the value of 0101%10 is calculated.
int dec1 = 0, rem1=0, num1, base1 = 1;
int a = 101;
while (a > 0){
rem1 = a % 10;
cout << rem1 << endl;
dec1 = dec1 + (rem1 * base1);
base1 = base1 * 2;
a = a / 10;
}
cout << dec1 << endl;
From this, I was able to see that right after 0101%10 is calculated, a value of 5 is stored in rem1, instead of 1.
Does adding this 0 in front of the MSB tell the compiler "hey, this number is in binary?" because if the compiler is reading 5%10 instead of 0101%10, then I guess the error makes sense.
Upon testing my theory, I changed 'a' to 1000 and the output was 8, which is correct.
Changing 'a' to 01000 gives a result of 24. rem1= 01000%10 should be 0, however rem1 is storing 2. 01000 binary = 8 decimal. 8%10=8? not 2?
I'm an unsure of what is going on and any help is appreciated!

101 is parsed as a decimal (base 10) number, so you get your expected output.
0101 is parsed as an octal (base 8) number due to the leading zero. The leading zero here works just like the leading 0x prefix that denotes a hexadecimal (base 16) number, except that without the x it's base 8 instead of base 16.†
1018 = 82 + 80 = 64 + 1 = 65
65 % 10 = 5
65 / 10 = 6
6 % 10 = 7
5 * 2 + 7 = 17
If I were you, I'd add an assert(rem1 == 0 || rem1 == 1) inside your loop right after your assignment to rem1 as a sanity check. If you ever get a remainder larger than one or less than zero then there's obviously something wrong.
As rbaleksandar points out in his comment above, the easiest way to avoid this issue is probably to store your input as a c-string (char[]) rather than using an integer literal. This is also nice because you can just iterate over the characters to compute the value instead of doing % and / operations.
Alternatively, you could use hex literals (e.g., 0x101 or 0x0101) for all of your inputs, and change your math to use base 16 instead of base 10. This has the added advantage that base 10 division and remainder functions can be optimized by the compiler into much cheaper bit-shift and bit-mask operations since 16 is a power of 2. (E.g., 0x101 % 16 ==> 0x101 & 15, and 0x101 / 16 ==> 0x101 >> 4).
† For more info
see http://en.cppreference.com/w/cpp/language/integer_literal

0101 is Octal number, which value is 17.

Related

Have some doubts in the operation [Bitwise Manipulation]

#include <iostream>
#include <math.h>
using namespace std;
// converting from decimal to binary
int main()
{
int n, bit, ans = 0, i = 0;
cout << "enter a number: ";
cin >> n;
while (n > 0)
{
bit = n & 1;
ans = round(bit * pow(10, i)) + ans; /* we used 'round' bcoz pow(10, 2) give 99.99999
it differs from compiler to compiler */
n = n >> 1;
i++;
}
cout << ans;
return 0;
}
I am unable to understand that in while(n>0), n will be stored as binary form or decimal form.
That is if n=5, so whether while loop check for (5>0) or (101>0).
Can anyone explain what is happening here?
I am new to this platform, please don't delete my question. My earlier questions are also gets deleted due enough dislikes. I am here to learn and am still learning.
"Decimal" and "Binary" are text representations of a value. n is an int, not text, so it holds the value 5. If I have 5 apples on a desk, then there is no "decimal" or "binary" involved. THere's just 5 apples. Same with int.
cin >> n;
while (n > 0)
This loop continues because 5 > 0.
n = n >> 1;
This is just a fancy way of writing n = n / 2, so then n becomes 2. Since 2 > 0, the loop continues. On the third run, n becomes 1, and since 1 > 0, the loop continues a third time. On the fourth run, n becomes 0, and 0 == 0, so the while loop exits.
Both n and ans are integers that your computer stores in a binary format. If n = 5 then n is both 5 and 0b0101. Your loop converts one integer n into a second integer ans which only uses the digits 1 and 0 and looks like the integer n in binary.
It does this by converting each power of two in n into a power of ten and adding it into ans. The integer 5 will become the integer 101 (one hundred and one).
In the loop, when you use the bitwise operator >> you are manipulating the underlying binary representation of the number directly, in this case, shifting all of the bits in the integer to the right and feeding in zeros on the left to replace the bits that have moved.
So, if n is 5 then:
0b0101 >> 1 gives 0b0010, or 2
0b0101 >> 2 gives 0b0001, or 1
0b0101 >> 3 gives 0b0000, or 0
When you use the bitwise operator & (bitwise and) you are again operating directly on the binary representation. This time you are and-ing all of the bits in one number with the bit in another number. For example:
0b01100110 & 0b10101110 = 0b00100110
0b01100110 & 0b10011001 = 0b00000000
In your loop you are doing four things:
1. bit = n & 1
And-ing the integer n with one will mean that bit is equal to:
1 when there is a 1 in the 2^0 place (the least significant bit) and,
0 when there is not a 1 in the 2^0 place.
2. ans = round(bit * pow(10, i)) + ans
You take 10^i and multiply it by bit. So:
bit is zero this is zero
if bit is one this is some power of ten.
3. n = n >> 1
Shift one place to the right. The bit that was in the 2^1 place is now in the 2^0 place.
4. i++
Increment i which tracks both your current power of 2 and current power of ten.
#Mooing Duck has explained it incredibly well. I'd just add that you are being confused about the Number System
Decimal numbers are called the base 10 numbers (digits: 0 - 9, total: 10)
Binary numbers are called the base 2 numbers(digits/bits: 0 - 1, total: 2)
101 (base 10) is very different from 101 (base 2)
When we use bitwise operators such as (<<, >>, &, ^, |) we manipulate the bits of the decimal (hence the name bitwise operators)
So, when you are doing 5 >> 1 you are actually doing 101 (base 2) >> 1 which results in 010 (base 2)
When you keep shifting the bits to the right(equivalent to dividing by 2), at one point you'll be left with no 1s and only 0s. And what's 0 (base 2)? Its 0(base 10). Hence, the loop breaks.

VBA convert Excel Style Column Name (with 52 charset) to original number

I have a c++ program that takes an integer and convert it to lower and uppercase alphabets, similar to what excel does to convert column index to column number but also including lower case letters.
#include <string>
#include <iostream>
#include <climits>
using namespace std;
string ConvertNum(unsigned long v)
{
char const digits[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
size_t const base = sizeof(digits) - 1;
char result[sizeof(unsigned long)*CHAR_BIT + 1];
char* current = result + sizeof(result);
*--current = '\0';
while (v != 0) {
v--;
*--current = digits[v % base];
v /= base;
}
return current;
}
// for testing
int main()
{
cout<< ConvertNum(705);
return 0;
}
I need the vba function to reverse this back to the original number. I do not have a lot of experience with C++ so I can not figure out a logic to reverse this in vba. Can anyone please help.
Update 1: I don't need already written code, just some help in the logic to reverse it. I'll try to convert the logic into code myself.
Update 2: Base on the wonderful explanation and help provided in the answer, it's clear that the code is not converting the number to a usual base52, it is misleading. So I have changed the function name to eliminate the confusion for future readers.
EDIT: The character string format being translated to decimal by the code described below is NOT a standard base-52 schema. The schema does not include 0 or any other digits. Therefore this code should not be used, as is, to translate a standard base-52 value to decimal.
O.K. this is based on converting a single character based on its position in a long string. the string is:
chSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
The InStr() function tells us the A is in position 1 and the Z is in position 26 and that a is in position 27. All characters get converted the same way.
I use this rather than Asc() because Asc() has a gap between the upper and lower case letters.
The least significant character's value gets multiplied by 52^0The next character's value gets multiplied by 52^1The third character's value gets multiplied by 52^3, etc. The code:
Public Function deccimal(s As String) As Long
Dim chSET As String, arr(1 To 52) As String
Dim L As Long, i As Long, K As Long, CH As String
chSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
deccimal = 0
L = Len(s)
K = 0
For i = L To 1 Step -1
CH = Mid(s, i, 1)
deccimal = deccimal + InStr(1, chSET, CH) * (52 ^ K)
K = K + 1
Next i
End Function
Some examples:
NOTE:
This is NOT the way bases are usually encoded. Usually bases start with a 0 and allow 0 in any of the encoded value's positions. In all my previous UDF()'s similar to this one, the first character in chSET is a 0 and I have to use (InStr(1, chSET, CH) - 1) * (52 ^ K)
Gary's Student provided a good and easy to understand way to get the number from what I call "Excel style base 52" and this is what you wanted.
However this is a little different from the usual base 52. I'll try to explain the difference to regular base 52 and its conversion. There might be an easier way but this is the best I could come up with that also explains the code you provided.
As an example: The number zz..zz means 51*(1 + 52 + 52^2 + ... 52^(n-1)) in regular base 52 and 52*(1 + 52 + 52^2 + ... 52^(n-1)) in Excel style base 52. So Excel style get's higher number with fewer digits. Here is how much that difference is based on number of digits. How is this possible? It uses leading zeros so 1, 01, 001 etc are all different numbers. Why don't we do this normally? It would mess up the easy arithmetic of the usual system.
We can't just shift all the digits by one after the base change and we can't just substract 1 before the base change to counter the fact that we start at 1 instead of 0. I'll outline the problem with base 10. If we'd use Excel style base 10 to number the columns, we would have to count like "0, 1, 2, ..., 9, 00, 01, 02, ...". On the first glance it looks like we just have to shift the digits so we start counting at 1 but this only works up to the 10th number.
1 2 .. 10 11 .. 20 21 .. 99 100 .. 110 111 //normal counting
0 1 .. 9 00 .. 09 10 .. 88 89 .. 99 000 //excel style counting
You notice that whenever we add a new digit we shift again. To counter that, we have to do a shift by 1 before calculating each digit, not shift the digit after calculating it. (This only makes a difference if we're at 52^k) Note that we still assign A to 0, B to 1 etc.
Normally what you would do to change bases is looping with something like
nextDigit = x mod base //determining the last digit
x = x/base //removing the last digit
//terminate if x = 0
However now it is
x = x - 1
nextDigit = x mod base
x = x/base
//terminate if x = 0
So x is decremented by 1 first! Let's do a quick check for x=52:
Regular base 52:
nextDigit = x mod 52 //52 mod 52 = 0 so the next digit is A
x = x/52 //x is now 1
//next iteration
nextDigit = x mod 52 //1 mod 52 = 1 so the next digit is B
x = x/52 //1/52 = 0 in integer arithmetic
//terminate because x = 0
//result is BA
Excel style:
x = x-1 //x is now 51
nextDigit = x mod 52 //51 mod 52 = 51 so the next digit is z
x = x/52 //51/52 = 0 in integer arithmetic
//terminate because x=0
//result is z
It works!
Part 2: Your C++ code
Now for let's read your code:
x % y means x mod y
When you do calculations with integers, the result will be an integer which is achieved by rounding down. So 39/10 will produce 3 etc.
x++ and ++x both increment x by 1.
You can use this in other statements to save a line of code. x++ means x is incremented after the statement is evaluated and ++x means it is incremented before the statement is evaluated
y=f(x++);
is the same as
y = f(x);
x = x + 1;
while
y=f(++x);
is the same as
x = x + 1;
y = f(x);
This goes the same way for --
Char* p creates a pointer to a char.
A pointer points to a certain location in memory. If you change the pointer, it points to a different location. E.g. doing p-- moves the pointer one to the left. To read or write the value that is saved at the location, use *p. E.g. *p="a"; "a" is written to the memory location that p points at. *p--="a"; "a" is written to the memory but the pointer is moved to the left afterwards so *p is now whatever is in the memory left of "a".
strings are just arrays of type char.
The end of a string is always '\0' if the computer reads a string it continues until it finds '\0'
This is hopefully enough to understand the code. Here it is
#include <string>
#include <iostream>
#include <climits>
using namespace std;
string base52(unsigned long v)
{
char const digits[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; //The digits. (Arrays start at 0)
size_t const base = sizeof(digits) - 1; //The base, based on the digits that were given
char result[sizeof(unsigned long)*CHAR_BIT + 1]; //The array that holds the answer
//sizeof(unsigned long)*CHAR_BIT is the number of bits of an unsigned long
//which means it is the absolute longest that v can be in any base.
//The +1 is to hold the terminating character '\0'
char* current = result + sizeof(result); //This is a pointer that is supposed to point to the next digit. It points to the first byte after the result array (because its start + length)
//(i.e. it will go through the memory from high to low)
*--current = '\0'; //The pointer gets moved one to the left (to the last char of result and the terminating char is added
//the pointer has to be moved to the left first because it was actually pointing to the first byte after the result.
while (v != 0) { //loop until v is zero (until there are no more digits left.
v--; //v = v - 1. This is the important part that does the 1 -> A part
*--current = digits[v % base]; // the pointer is moved one to the left and the corresponding digit is saved
v /= base; //the last digit is dropped
}
return current; //current is returned, which points at the last saved digit. The rest of the result array (before current) is not used.
}
// for testing
int main()
{
cout<< base52(705);
return 0;
}

Write a program using bitwise operators to determine positive remaindar

Write a program that reads an integer value from the keyboard into a variable of type int, and uses one of the bitwise operators (i.e. not the % operator!) to determine the positive remainder when divided by 8.
For example, 29 = (3x8)+5 and 14 = ( 2x8)+2 have positive remainder 5 and 2, respectively, when divided by 8.
I tried to search how can I solve it. What I did is to break given examples numbers into binary.
29 => 101001
8 => 001000
5 => 000101
I don't know what is operation I should do with 29 and 8 to get result 5 in binary.
While searching there's some guys said that we should do (& operation with 7 )
remainder = remainder & 7 ;
Then I tried to do this with Value itself
value = value & 7 ;
and Here's my code After doing it ...
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int value = 0;
int divisor = 8;
int remainder = 0;
cout << "Enter an integr and I'll divide it by 8 and give you the remainder!"
<<endl;
cin >> value;
value = value & 7;
remainder = value & divisor;
cout << remainder;
return 0;
}
It gave me result 0 when I use value 29. I don't know what I wrote was right or not.
Simply & the number itself with 7. Also, 29 = 0b11101. To generalise, the remainder when divided by a number 2 ^ n is found by &ing it with (2 ^ n) - 1 (^ == power of)
Thus, to obtain remainder modulo 16, & with 15, and so on.
Since 8 is exactly 2^3, the modulo-8 remainder of any number is composed of its last three binary digits, i. e. it equals the number bitwise-and 7:
unsigned rem8 = number & 7;
(7 is 111 in binary, that's why.)

C++ what does >> do

What does >> do in this situation?
int n = 500;
unsigned int max = n>>4;
cout << max;
It prints out 31.
What did it do to 500 to get it to 31?
Bit shifted!
Original binary of 500:
111110100
Shifted 4
000011111 which is 31!
Original: 111110100
1st Shift:011111010
2nd Shift:001111101
3rd Shift:000111110
4th Shift:000011111 which equals 31.
This is equivilent of doing integer division by 16.
500/16 = 31
500/2^4 = 31
Some facts pulled from here: http://www.cs.umd.edu/class/spring2003/cmsc311/Notes/BitOp/bitshift.html (because blarging from my head results in rambling that is unproductive..these folks state it much cleaner than i could)
Shifting left using << causes 0's to be shifted from the least significant end (the right side), and causes bits to fall off from the most significant end (the left side).
Shifting right using >> causes 0's to be shifted from the most significant end (the left side), and causes bits to fall off from the least significant end (the right side) if the number is unsigned.
Bitshifting doesn't change the value of the variable being shifted. Instead, a temporary value is created with the bitshifted result.
500 got bit shifted to the right 4 times.
x >> y mathematically means x / 2^y.
Hence 500 / 2^4 which is equal to 500 / 16. In integer division the result is 31.
It divided 500 by 16 using integer division.
>> is a right-shift operator, which shifted the bits of the binary representation of n to the right 4 times. This is equivalent to dividing n by 2 4 times, i. e. dividing it by 2^4=16. This is integer division, so the decimal part got truncated.
It shifts the bits of 500 to the right by 4 bit positions, tossing out the rightmost bits as it does so.
500 = 111110100 (binary)
111110100 >> 4 = 11111 = 31
111110100 is 500 in binary. Move the bits to the right and you are left with 11111 which is 31 in binary.
500 in binary is [1 1111 0100]
(4 + 16 + 32 + 64 + 128 + 256)
Shift that to the right 4 times and you lose the lowest 4 bits, resulting in:
[1 1111]
which is 1 + 2 + 4 + 8 + 16 = 31
You can also examine it in Hex:
500(decimal) is 0x1F4(hex).
Then shift to the right 4 bits, or one nibble:
0x1F == 31(dec).
The >> and << operators are shifting operators.
http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Companion/cxx_crib/shift.html
Of course they may be overloaded just to confuse you a little more!
C++ has nice classes to animate what is going on at the bit level
#include <bitset>
#include <iostream>
int main() {
std::bitset<16> s(500);
for(int i = 0; i < 4; i++) {
std::cout << s << std::endl;
s >>= 1;
}
std::cout << s
<< " (dec " << s.to_ulong() << ")"
<< std::endl;
}

How to check for division by 7 for big number in C++?

I have to check, if given number is divisible by 7, which is usualy done just by doing something like n % 7 == 0, but the problem is, that given number can have up to 100000000, which doesn't fit even in long long.
Another constrain is, that I have only few kilobytes of memory available, so I can't use an array.
I'm expecting the number to be on stdin and output to be 1/0.
This is an example
34123461273648125348912534981264376128345812354821354127346821354982135418235489162345891724592183459321864592158
0
It should be possible to do using only about 7 integer variables and cin.get(). It should be also done using only standard libraries.
you can use a known rule about division by 7 that says:
group each 3 digits together starting from the right and start subtracting and adding them alternativly, the divisibility of the result by 7 is the same as the original number:
ex.:
testing 341234612736481253489125349812643761283458123548213541273468213
549821354182354891623458917245921834593218645921580
(580-921+645-218+593-834+921-245+917-458+623-891+354-182
+354-821+549-213+468-273+541-213+548-123+458-283+761-643
+812-349+125-489+253-481+736-612+234-341
= 1882 )
% 7 != 0 --> NOK!
there are other alternatives to this rule, all easy to implement.
Think about how you do division on paper. You look at the first digit or two, and write down the nearest multiple of seven, carry down the remainder, and so on. You can do that on any abritrary length number because you don't have to load the whole number into memory.
Most of the divisibility by seven rules work on a digit level, so you should have no problem applying them on your string.
You can compute the value of the number modulo 7.
That is, for each digit d and value n so far compute n = (10 * n + d) % 7.
This has the advantage of working independently of the divisor 7 or the base 10.
You can compute the value of the number modulo 7.
That is, for each digit d and value n so far compute n = (10 * n + d) % 7.
This has the advantage of working independently of the divisor 7 or the base 10.
I solved this problem exactly the same way on one of programming contests. Here is the fragment of code you need:
int sum = 0;
while (true) {
char ch;
cin>>ch;
if (ch<'0' || ch>'9') break; // Reached the end of stdin
sum = sum*10; // The previous sum we had must be multiplied
sum += (int) ch;
sum -= (int) '0'; // Remove the code to get the value of the digit
sum %= 7;
}
if (sum==0) cout<<"1";
else cout<<"0";
This code is working thanks to simple rules of modular arithmetics. It also works not just for 7, but for any divisor actually.
I'd start by subtracting some big number which is divisible by 7.
Examples of numbers which are divisible by 7 include 700, 7000, 70000, 140000000, 42000000000, etc.
In the particular example you gave, try subtracting 280000000000(some number of zeros)0000.
Even easier to implement, repeatedly subtract the largest possible number like 70000000000(some number of zeros)0000.
Because I recently did work dealing with breaking up numbers, I will hint that to get specific numbers - which is what you will need with some of the other answers - think about integer division and using the modulus to get digits out of it.
If you had a smaller number, say 123, how would you get the 1, the 2, and the 3 out of it? Especially since you're working in base 10...
N = abc
There is a simple algorithm to verify if a three-digit number is a multiple of 7:
Substitute a by x and add it to bc, being x the tens of a two-digit number multiple of 7 whose hundreds is a.
N = 154; x = 2; 2 + 54 = 56; 7|56 and 7|154
N = 931; x = 4; 4 + 31 = 35; 7|35 and 7|931
N = 665; x = 5; 5 + 65 = 70; 7|70 and 7|665
N = 341; x = 6; 6 + 41 = 47; 7ł47 and 7ł341
If N is formed by various periods the inverse additive of the result of one period must be added to the sum of the next period, this way:
N = 341.234
6 + 41 = 47; - 41 mod 7 ≡ 1; 1 + 4 + 34 = 39; 7ł39 and 7łN
N = 341.234.612.736.481
The result for 341.234 is 39. Continuing from this result we have:
-39 mod 7 ≡ 3; 3 + 5 + 6 + 1 + 2 + 1 = 18; - 18 mod 7 ≡ 3; 3 + 0 + 36 = 39; - 39 mod 7 ≡ 3;
3 + 1 + 81 = 85; 7ł85 and 7łN
This rule may be applied entirely through mental calculation and is very quick.
It was derived from another rule that I created in 2.005. It works for numbers of any magnitude and for divisibility by 13.
At first Take That Big Number in string And then sum every digit of string. at last check if(sum%7==0)
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long int n,i,j,sum,k;
sum=0;
string s;
cin>>s;
for(i=0;i<s.length();i++)
{
sum=sum+(s[i]-'0');
}
if(sum%7==0)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
return 0;
}