Reputation: 141
I've made a program to represent any number from decimal to binary in c++, but when I try with negative numbers it gives me results like this: -1-1-1-11-1-0, i don't know why. I used a short int to represent the numbers from -32000 to 32000 also i used unsigned to get bigger numbers. Also i used an array to store the numbers and than reverse them to have the correct representation. I don't think this is the correct way to reverse an array but it works for me.The MAX(16 ) is for store the rest in an array that is 16 bits. Here is the code:
#include <iostream>
using namespace std;
const int MAX=16;
int main(){
int tab1[MAX];
short int n;
cout<<"Input a number: ";
cin>>n;
for (int i=0; i<sizeof(n)*8; i++){
tab1[i] = n%2;
n = n>>1;
}
cout<<"Binary representation: ";
for (int j=MAX-1;j>=0;j--){
cout<<tab1[j];
}
cout<<endl;
return 0;
}
Upvotes: 0
Views: 169
Reputation: 41168
Your shifting process preserves the fact that the sign bit is flipped so everything you extract out has the sign bit. Mask it out by using a bitwise and ( tab[i]=n&1
) rather than using the %
which in C keeps the negative sign.
The %
operator in C is not the modulo operator but the remainder operator. With a remainder operator the sign of the result is the same as the sign of the dividend. With a modulo operator the sign of the result is the same as the divisor.
Upvotes: 1