how to output an int in binary?

后端 未结 5 1575
醉梦人生
醉梦人生 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<const char*>(&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<const char*>(&transport), sizeof(u_long));
    

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

    std::cout << x;
    
    0 讨论(0)
  • 2020-12-09 18:33

    A bit late, but, as Katy shows in her blog, this might be an elegant solution:

    #include <bitset>
    #include <iostream>
    
    int main(){
      int x=5;
      std::cout<<std::bitset<32>(x)<<std::endl;
    }
    

    taken from: https://katyscode.wordpress.com/2012/05/12/printing-numbers-in-binary-format-in-c/

    0 讨论(0)
  • 2020-12-09 18:34

    and what about this?

    int x = 5;
    cout<<(char) ((0xff000000 & x) >> 24);
    cout<<(char) ((0x00ff0000 & x) >> 16);
    cout<<(char) ((0x0000ff00 & x) >> 8);
    cout<<(char) (0x000000ff & x);
    

    0 讨论(0)
  • 2020-12-09 18:40

    You can use the std::ostream::write() member function:

    std::cout.write(reinterpret_cast<const char*>(&x), sizeof x);
    

    Note that you would usually want to do this with a stream that has been opened in binary mode.

    0 讨论(0)
  • 2020-12-09 18:45

    A couple of hints.

    First, to be between 0 and 2^32 - 1 you'll need an unsigned four-byte int.

    Second, the four bytes starting at the address of x (&x) already have the bytes you want.

    Does that help?

    0 讨论(0)
提交回复
热议问题