Hello (sorry if i break any rules on post format first time on daniweb)Have a project to make a binary to hex,Dec,octal. Now i found this code here
http://www.daniweb.com/forums/post598839.html#post598839 and made a few changes to it but i am not familiar with a few of the parts and some help would be appreciated (didn't know how to highlight so put // on the line and question on what it does)

#include <iostream>
#include <iomanip> // what is this library used for 
#include <string>
#include <bitset>
using namespace std; 
int main()
{
  std::cout << "Enter a binary number: ";

  std::string bin;

  if (getline(std::cin, bin)) {
    bitset<32> bits(bin);
	cout <<"Octal  ";
    cout << std::oct << bits.to_ulong() << '\n'; //what does the bits.to_ulong() part do or what is it tied to . 
	cout <<"Hex   ";
    cout << std::hex << bits.to_ulong() << '\n';
	cout <<"dec   ";
	cout << std::dec << bits.to_ulong() << '\n';
  }

return 0;
}
Narue commented: For considering the rules and proper use of code tags. +26

Recommended Answers

All 2 Replies

>#include <iomanip> // what is this library used for
The <iomanip> header essentially declares stream manipulators that take an argument. This is as opposed to those stream manipulators that don't take a special argument and are declared in the <ios> header.

The code you posted is actually incorrect in that it includes <iomanip>, but uses manipulators that are declared in <ios> (std::oct, std::dec, and std::hex). However, due to the common inclusion of <ios> by <iostream>, it works as intended. I'd recommend that you drop <iomanip> and include <ios> directly for maximum portability. I'd also recommend explicitly qualifying your standard names with std:: and not abusing the using directive:

#include <iostream>
#include <ios>
#include <string>
#include <bitset>

int main()
{
  std::cout << "Enter a binary number: ";

  std::string bin;

  if (getline(std::cin, bin)) {
    std::bitset<32> bits(bin);
    std::cout <<"Octal  ";
    std::cout << std::oct << bits.to_ulong() << '\n'; 
    std::cout <<"Hex   ";
    std::cout << std::hex << bits.to_ulong() << '\n';
    std::cout <<"dec   ";
    std::cout << std::dec << bits.to_ulong() << '\n';
  }

  return 0;
}

>//what does the bits.to_ulong() part do or what is it tied to .
to_ulong takes the bit pattern stored in bits and copies it in an unsigned long value. The result is that the bit pattern "11011" will produce 27 when you call to_ulong() and print the value as a decimal number.

Ok thank you for the reply.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.