How can I convert hexadecimal numbers to binary in C++?

后端 未结 6 419
星月不相逢
星月不相逢 2020-12-05 06:08

I am taking a beginning C++ class, and would like to convert letters between hex representations and binary. I can manage to print out the hex numbers using:



        
6条回答
  •  情深已故
    2020-12-05 06:26

    There isn't a binary io manipulator in C++. You need to perform the coversion by hand, probably by using bitshift operators. The actual conversion isn't a difficult task so should be within the capabilities of a beginner at C++ (whereas the fact that it's not included in the standard library may not be :))

    Edit: A lot of others have put up examples, so I'm going to give my preferred method

    void OutputBinary(std::ostream& out, char character)
    {
      for (int i = sizeof(character) - 1; i >= 0; --i)
      {
        out << (character >> i) & 1;
      }
    }
    

    This could also be potentially templated to any numeric type.

提交回复
热议问题