how to output an int in binary?

后端 未结 5 1629
醉梦人生
醉梦人生 2020-12-09 17:41
int x = 5;
cout<<(char)x;

the code above outputs an int x in raw binary, but only 1 byte. what I need it to do is output the x as 4-bytes in

5条回答
  •  被撕碎了的回忆
    2020-12-09 18:22

    Try:

    int x = 5;
    std::cout.write(reinterpret_cast(&x),sizeof(x));
    

    Note: That writting data in binary format is non portable.
    If you want to read it on an alternative machine you need to either have exactly the same architecture or you need to standardise the format and make sure all machines use the standard format.

    If you want to write binary the easiest way to standardise the format is to convert data to network format (there is a set of functions for that htonl() <--> ntohl() etc)

    int x = 5;
    u_long  transport = htonl(x);
    std::cout.write(reinterpret_cast(&transport), sizeof(u_long));
    

    But the most transportable format is to just convert to text.

    std::cout << x;
    

提交回复
热议问题