#include <iostream>
usingnamespace std;
// function to convert decimal to binary
void decToBinary(int n)
{
// array to store binary number
int binaryNum[32];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
// Driver program to test above function
int main()
{
int n = 10000;
decToBinary(n);
return 0;
}
Output:
10011100010000
I want change out put like this [ by code] :
110111000100010
#include <iostream>
// function to convert decimal to binary
void decToBinary(int n) {
// array to store binary number
int binaryNum[32] {};
// counter for binary array
for (size_t i {}; n > 0; ++i, n /= 2)
// storing remainder in binary array
binaryNum[i] = n % 2;
// printing binary array in reverse order
for (size_t j = 32; j > 0; --j)
std::cout << binaryNum[j - 1];
}
// Driver program to test above function
int main() {
decToBinary(10000);
}
00000000000000000010011100010000
This can also be done simply using std::bitset:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
#include <bitset>
// function to convert decimal to binary
void decToBinary(unsigned n) {
std::cout << std::bitset<32> {n} << '\n';
}
// Driver program to test above function
int main() {
decToBinary(10000);
}
Well changing 100111 to 110111 is easy. Just change the appropriate element in the array. Adding an extra bit is best done with using a std::vector. Or use the std::bitset: