Here is the code to compute: anyone, with help to convert a signed integer to its binary equivalent (8 bits) (in 2's complement) and vice versa. The program should be able t0 first read in either a signed integer or a binary number (always in 2's complement) provided by the user
For example, when I input 00110101
to convert to signed decimal, I will get 203
. But the correct answer is 53
.
#include <iostream>
#include <string>
using namespace std;
string decimalToBinary(int);
string findTwosComplement(string);
string decimalToBinary(int n) {
if (n < 0)
n = 256 + n;
string res = "";
while (n > 0)
{
res = string(1, (char)(n % 2 + 48)) + res;
n = n / 2;
}
return res;
}
string decimalToBinary(int n) {
if (n < 0)
n = 256 + n;
string res = "";
while (n > 0)
{
res = string(1, (char)(n % 2 + 48)) + res;
n = n / 2;
}
return res;
}
string findTwosComplement(string s)
{
int num = s.length();
int i;
for (i = num - 1; i >= 0; i--)
if (s[i] == '1')
break;
if (i == -1)
return '1' + s;
for (int j = i - 1; j >= 0; j--)
{
if (s[j] == '1')
s[j] = '0';
else
s[j] = '1';
}
return s;
}
I am assuming you want this for didactic purpose, other wise you just do (signed char) n
.
The two complements is -2<<(n-1) + sum(2<<k for 0 <= k < n-1)
so for 8-bit you have the usual binary representation for the numbers 0 <= N < 128
the difference is that the most significant bit is not adding 128, but subtracting 128. This is why it can represent numbers -128 <= N < 128
. Important thing is that you can increase the width of the number by replicating the signal digit. C++ numbers are already 2-complements 32-bit numbers, so for the numbers in the valid range the 24 most significant bits are either all '0' or all '1', so you can just slice the bits there.
#include <iostream>
#include <string>
using namespace std;
string decimalToBinary(int n) {
// C++ integers are already in 2-complements so you only have to
// extract the bits.
if((n < -128) || (n >= 128)){
std::cerr << "The number "<< n << " does not fit into a 8-bit 2-complement representation" << std::endl;
}
string res = "";
for(int i = 0; i < 8; ++i){
res = string(1, (char)(((n >> i) & 1) + '0')) + res;
}
return res;
}
int binaryToDecimal(string s) {
// The most significant bit is the signal
int result = -((int)(s[0] - '0'));
for(int i = 1; i < s.size(); ++i){
result = 2*result + ((int)(s[i] - '0'));
}
return result;
}
int main(){
int input;
while(cin){
cout << "> ";
cin >> input;
string binary = decimalToBinary(input);
int output = binaryToDecimal(binary);
cout << input << " -> " << binary << " -> " << output << endl;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.