The assignment is to convert a decimal value to an 8-bit twos complement binary. The input needs to range between -128 & 127. Currently, my program only works for positive numbers. I am fairly new at coding so I've been stuck, and would appreciate any help.
#include <iostream>
#include <string>
using namespace std;
int DecimalToBinary(int dec);
int main() {
    int userInput;
    cout << "Enter a value: ";
    cin >> userInput;
    if (userInput >= -128 && userInput <= 127) {
        int dec = userInput;
        cout << userInput << " = ";
        DecimalToBinary(dec);
    }
    else {
        cout << "Enter a value between -128 and 127: ";
        cin >> userInput;
        if (userInput >= -128 && userInput <= 127)
        {
            int dec = userInput;
            cout << userInput << " = ";
            DecimalToBinary(dec);
        }
    }
    return 0;
}
int DecimalToBinary(int dec)
{
    int bin[1000] = {};     // array to store binary number
    int i = 0;
    while (dec > 0) {       //calculating the binary
        bin[i] = dec % 2;   //storing remainder
        dec = dec / 2;
        ++i;
    }
    // printing binary in 8 bit & reverse order
    int bits = 8;
    if (i > 8) {
        bits = 8 * ((i + 7) / 8);
    }
    for (int j = bits - 1; j >= 0; j--) {
        cout << bin[j];
    }
    return dec;;
}
 
    
 
    