Вопрос

So I know there is a way to convert Dec to binary using the bitset library but can you do the same for binary to decimal using the bitset library? or do you have to do it manually?

bitset<8> bin_x(number);
Это было полезно?

Решение

You can, but it should be a string.

std::bitset<8> bits("1111");
std::cout << bits.to_ulong() << std::endl;

You can convert your integer to string and then pass it to bitset c-tor.

Live example

Другие советы

Another easy way (without using bitset library) using stoi

// #include <string>
std::string str = "-10010110001";
int dec = std::stoi(bin, nullptr, 2); // dec = -1201
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top