Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c++ - how to output an int in binary?

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 binary, because in my code, x can be anywhere between 0 and 2^32-1, since

cout<<(int)x;

doesn't do the trick, how would I do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...