Другие языки программирования и технологии

Программа C++ Напишите программу которая переводит из десятичной в двоичную систему счисления (C++)

#include <iostream>
#include <windows.h>
#include <bitset>
#include <string>

using namespace std;

int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
system("color 0A");

cout << "Введите число ";
int n;
cin >> n;
bitset<32u> bs(n);
auto flag = false;
for (short u = 31; u >= 0; --u)
{
flag = bs[u] == 0? flag : true;
cout << (flag? to_string(bs[u]) : "");
}
cout << endl;

system("pause");
return 0;
}
Константин Меркулов
Константин Меркулов
8 552
Лучший ответ
Один из кучи методов, без незначащих нулей:

#include < iostream>
#include < string>

int main() {
int n;
std::cin >> n;
std::string bin;
int temp = n;

do {
if (temp % 2)
bin.push_back('1');
else
bin.push_back('0');
temp /= 2;
} while (temp);

if (n < 0)
bin.push_back('-');

for (auto it = bin.crbegin(); it != bin.crend(); ++it)
std::cout << *it;

return 0;
}
Петро Ралик
Петро Ралик
20 861
Хеххе

#include <iostream>

int main(){
unsigned x, r;
std::cin >> x;

for(char i=r=0;x>>i>0;i++)(r<<=1)^=x>>i&1;for(;r;r>>=1)std::cout<<(r&1);if(!(x%2))std::cout<<0;

std::cout << std::endl;
return 0;
}
не забыть подключить нужные библиотеки.

void printBits(size_t const size, void const * const ptr)
{
unsigned char *b = (unsigned char*) ptr;
unsigned char byte;
int i, j;

for (i=size-1;i>=0;i--)
{
for (j=7;j>=0;j--)
{
byte = (b[i] >> j) & 1;
printf("%u", byte);
}
}
puts("");
}

int main(int argv, char* argc[])
{
int i = 23;
uint ui = UINT_MAX;
float f = 23.45f;
printBits(sizeof(i), &i);
printBits(sizeof(ui), &ui);
printBits(sizeof(f), &f);
return 0;
}

Похожие вопросы