#include <iostream> using namespace std; int main() { long int b2 = 0; long int i = 1; int x; cout << "Enter a number:" ; cin >> x ; int y = x; while (x!=0) { if ( x%2 ) { b2 = b2 + i; } i = i*10; x=x/2; } cout << "Number " << y << " in base(2) is: " << b2; } This code transforms any number from base 10 to binary. There is only one problem, if I change any of the variable b2 or i to int instead of long int and I insert a number great than 1000 I get some weird results, sometimes negatives. I'm using Ubuntu 18.04 and code::blocks to compile. I researched but couldn't really find an answer. The int has 4 bytes which means 2^32 possibilities. It should work...
intto be at least 16-bit long, while it defineslong intto be at least 32-bits long.int, you are actually writing a base 10 number using only1and0. You are wasting the vast majority of your 2^32 possibilities.i = i*10;That can get really large really fast.INT_MAX = 2,147,483,647so after 9 bits you'll overflow since10^10 = 10,000,000,000.