Decimal to Binary

Hello, I have never done C++ before and I am having trouble writing a program in lab. This is due pretty soon and I really need help. Can someone write a program for me. It would really help me understand what I am learning and will save my lab grade. Please help!

Write a C++ application program to accept a signed decimal integer as input and output the equivalent 2s complement version in 16-bit binary. Include a space between every four bits in the output string. The input will only be processed by the application if it falls in the valid range that can be represented in 2s complement format with 16 bits. The range of a decimal number from - to + is -32768 to 32767. This is literally do in a hour!!!
No one is going to do your homework for you man.
Huh, why do I even bother...
closed account (2UD8vCM9)
Good luck.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;

string IntegerToString2sComp(int Integer)
{
	if (Integer < -32768 || Integer>32767)
		return "";
	string result;
	for (int bit = 0; bit < sizeof(int) * 4; ++bit)
	{
		int bit_val = 1 & Integer;
		result = (bit_val ? "1" : "0") + result;
		Integer = Integer >> 1;
	}
	return result;
}

int main()
{
	string TwosComplementAsString;
	int NumberToConvert = 0;
	cout << "Enter a number to convert to Two's Compliment between -32768 and 32767:";
	cin >> NumberToConvert;
	while (NumberToConvert>32767 || NumberToConvert < -32768)
	{
		cout << "Incorrect Input. Please enter a number between -32768 and 32767:";
		cin >> NumberToConvert;
	}
	TwosComplementAsString = IntegerToString2sComp(NumberToConvert);
	cout << "Integer " << NumberToConvert << " as Two's Complement:" << endl;
	for (int i = 0; i < TwosComplementAsString.size(); i += 4)
	{
		cout << TwosComplementAsString[0+i] << TwosComplementAsString[1+i] << TwosComplementAsString[2+i] << TwosComplementAsString[3+i] << " ";
	}
	cout << endl;
	return 0;
}
Last edited on
Topic archived. No new replies allowed.