C++格式化输出一:八进制,十进制,十六进制,二进制输出

来源:互联网 发布:mac综艺体字体下载 编辑:程序博客网 时间:2024/05/29 16:04

在 《数据结构与算法分析C++语言描述》第二版中 P184

有段八进制,十进制,十六进制输出的代码,如下所示:

int i = 17;

std::cout << showbase << oct << i << endl<< dec << i << endl<< hex << i << endl;

输出结果:

021170x11
八进制输出: oct

十进制输出: dec

十六进制输出:  hex

其中的 showbase用来显示进制前的符号;如:八进制0,十进制:没有, 十六进制的0x

noshowbase可以取消前缀。如http://www.cplusplus.com/reference/ios/showbase/中:

 std::cout << std::hex << std::showbase << n << '\n'; std::cout << std::hex << std::noshowbase << n << '\n';
Output:
0x1414


那么二进制输出,又怎么写呢?到目前为止,我觉得好像没有现成类似于oct,hex等格式输出。

不过在http://groups.engin.umd.umich.edu/CIS/course.des/cis400/cpp/binary.html网页上,有这样一段代码。略加修改后:

#include <iostream>using namespace std;void binary(int);int main(void) {    int number;    cout << "Please enter a positive integer: ";    cin >> number;    if (number < 0)        cout << "That is not a positive integer.\n";    else {        cout << number << " converted to binary is: ";        binary(number);                // 进入,退出        cout << endl;    }    return 0;}void binary(int number) {    int remainder;// 100    if (number <= 1) {                // 使用number >> 1移位操作,那么移到什么时候截止呢?        // 当只剩下最后一位数时,那么最后一位的值为0,或者1,所以它的值是小于等于0,否则        // 根据8421码,如果剩下两位数,那么最小的数应该是2, 二进制数(0010) = 十进制2        // 当输入100时,最终number=1,首先输出的数也是1        cout << number << endl;        // 输出最后一位数。        return;                            // 退出    }    remainder = number % 2;            // 0    binary(number >> 1);            //  自调用,到这里的时候,调用进入下一个binary入口。(退出时,也从这里退出)    cout << remainder<< endl;        }
// 递归转非递归:

// while 循环:void binary(int number) {    int remainder = 0;    vector<int> temp;    while (number >= 1){                        remainder = number % 2;        temp.push_back(remainder);        number = number >> 1;    }    while (temp.size()>0){        cout << temp.back();        temp.pop_back();    }    }
// for 循环(额,好像很多人的博客,如csdn或者sina中的博客,这个for循环好像写的都不太对。

说到这里,悄悄地问一句,有没红包呢吐舌头?敲代码不容易滴,我的手指呜呜呜,都变短变粗了快哭了。QQ:1058362683):

  void binary(int number) {    int remainder = 0;    vector<int> temp;    while (number >= 1){                        remainder = number % 2;        temp.push_back(remainder);        number = number >> 1;    }/*不要删除此段注释,author:朱勇date: 2015年11月13日 17:17:47*/  for (auto iter = temp.end(); iter > temp.begin();iter--){        cout << *(iter-1);    }   } 

使用字符串的方式:

在stackoverflow中,http://codereview.stackexchange.com/questions/51453/converting-an-integer-to-binary-hex-and-octal,Jamal给了一些建议

I'll just address several things regarding good practice. This can probably be simplified greatly overall, but I won't try to focus on that particularly.

main():

  • I don't see the need for if (number == 0), especially in relation toparse(). Are you just skipping further calculation if the return is0? If you do that, the outputs at the end will not be printed, even though0is a valid number.

  • You don't need to use std::endl in main(). That also flushes the buffer, which is unnecessary here, and you do it multiple times. Just use"\n" within a print statement.

parse():

  • You can define it above main(), allowing you to remove the function prototype.
  • It doesn't need the command line parameters; only main() does.
  • Its control paths and returns don't make sense to me. If the if statement is executed, it displays a message and returns0. If theelse is executed, it returns a convertedinteger. Instead, the function should only be calledif it will parse something, which is its main job. Functions should focus on just one thing. Let the calling code decide if it should be called.

Header:

  • There's no need for protected if you're not using inheritance (I believe even Bjarne Stroustrup himself has regretted adding that keyword). Either change it toprivate, or just remove the keyword since classes are private by default.

  • If you're not maintaining one or more data members, then this program may not need to utilize classes. This one just contains functions, but class functions are supposed tochange the state of one or more data members. Instead, those functions could just be free functions (non-member) and the class removed entirely.

Other:

  • This:

    if (number % 2 == 0){    result.append("0");}else{    result.append("1");}

    can just be made into a single-ternary statement:

    (number % 2 == 0) ? result.append("0") : result.append("1");

    Better yet, since std::string supports +=, use that instead:

    result += (number % 2 == 0) ? "0" : "1";
  • The local variables in int_to_bin() don't need to be static.

  • You don't need your own reverse function; just use std::reverse().

  • As @rachet freak has mentioned in the comments, you can just use std::hex to manipulate the I/O when displaying this value. In addition, you can do this withall three number systems.


我尝试将其转化成C++程序(当然,他已经把重要的事情已经写出来了):

#include <iostream>#include<stdlib.h>#include<vector>#include<string>// 没有这句会提示错误    // 没有与这些操作数匹配的 "<<" 运算符操作数类型为:  std::ostream << std::stringusing namespace std;int main(void) {    int number = 0;    cin >> number;    std::string result;    while (number>=1)    {        if (number % 2 == 0)            result.append("0");        else            result.append("1");// (number % 2 == 0) ? result.append("0") : result.append("1");//result += (number % 2 == 0) ? "0" : "1";        number = number >> 1;    }        std::reverse(std::begin(result), std::end(result));    cout << result;                    // #include<string> , #include<iostream>    return 0;}
输入:100

输出:1100100
注意,将std::string使用cout输出时,除了要添加iostream外,还需要添加string头文件。否则会有如下报错:

没有与这些操作数匹配的 "<<" 运算符操作数类型为:  std::ostream << std::string

在ttp://stackoverflow.com/questions/6320995/why-i-cannot-cout-a-string中

Why I cannot cout a string?的提问

Ata 和Kiril Kirov 是这样回答的

You need to include

#include <string>#include <iostream>

今天突然发现还有一种方式  ----  使用bitset:

#include <iostream>#include <bitset>using namespace std;int main(){    int num;    cin>>num;    bitset<64> b(num);                      // 64bit 的二进制数    for(int i=63 ;i>=0; --i){        cout << b[i];    }    cout<<endl;    cout<<b<<endl;    b.to_string();    cout<<b;    return 0;}
输出:

100000000000000000000000000000000000000000000000000000000000110010000000000000000000000000000000000000000000000000000000000011001000000000000000000000000000000000000000000000000000000000001100100

统计bitset中0和1的位数:

// bitset::count#include <iostream>       // std::cout#include <string>         // std::string#include <bitset>         // std::bitsetint main (){  std::bitset<8> foo (std::string("10110011"));  std::cout << foo << " has ";  std::cout << foo.count() << " ones and ";  std::cout << (foo.size()-foo.count()) << " zeros.\n";  return 0;}


1 0
原创粉丝点击