Language : C++
/****************
Convert any -ve integer to binary
return int
if the number 0101 (which represents +5) is stored in a 4-bit word, its extension to an
8-bit word would be 0000 0101. Conversely, the extension of the 4-bit number 1101 (representing -3) to
an 8-bit word results in 1111 1101. This method ensures that the signed values remain unchanged after the
extension.
****************/
#include <iostream>
#include <climits>
unsigned long long int toBinary(int n) {
if (n >= 0) {
std::cout << "Sorry, wrong input" << std::endl;
return 0;
}
int m = ~n; //1's complement of n ... introduced to execute right shift
unsigned long long int num = 0;
unsigned long long int pow10 = 1;
while (m) {
num = (!(m & 1) * pow10) + num;
m >>= 1;
if (pow10 > ULLONG_MAX / 10 && m) {
std::cout << "Sorry, storage issue" << std::endl;
return 0;
}
pow10 *= 10;
}
num = pow10 + num;
return num;
}
int main() {
int n;
std::cout << "Enter a negative integer: ";
std::cin >> n;
if (!(toBinary(n)));
else {
printf("%32llu\n", toBinary(n));
printf("Replace space padding with 1 :)\n");
}
std::cin.get();
}

Comments
Post a Comment