How to print (using cout) a number in binary form?
The easiest way is probably to create an std::bitset
representing the value, then stream that to cout
.
#include <bitset>
...
char a = -58;
std::bitset<8> x(a);
std::cout << x << '\n';
short c = -315;
std::bitset<16> y(c);
std::cout << y << '\n';
how to output an int in binary?
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.
printing the binary representation of a number
You're starting at the least significant bit in the number and printing it first. However, whatever you print first is the most significant digit in the typical binary representation.
65 is 01000001
so this is how your loop iterates
01000001
^ Output: 1
01000001
^ Output: 10
01000001
^ Output: 100
...
01000001
^ Output: 10000010
Thus the printed output is in reverse. The simplest fix is to change the order of the loop.
for (int i = 7; i >= 0; i--) {
cout << ((a >> i) & 1);
}
Error meaning; printing a number in binary form
There are two issues: First, the compiler is warning about an implicit type conversion in the code. Second, the compiler is treating warnings as errors, causing the build to fail.
The bitset takes a parameter of type unsigned long int, but you are attempting to pass a (signed) short int. You know it will promote the signed value as a two's complement value, and do what you expect, but the compiler is not sure you understand this, and will issue a warning. The most fundamental way to fix this is by type casting, which tells the compiler, explicitly, to make the conversion. There are multiple ways to do this. The simplest and most readable is the older C style cast, which also works in C++:
std::bitset<16> y((unsigned long)c);
An alternative in C++ style:
std::bitset<16> y(static_cast<unsigned long>(c));
More on warnings-as-errors:
A Werror is a compiler flag that treats warnings as errors. While treating warnings as errors can enforce rigor by now letting you proceed without explicitly addressing warnings in some manner, this can also be burdensome when maintaining a large code base that you didn't write. To disable the specific warning-as-error you saw, you'd change it to Wno-error:
-Wno-error=sign-conversion
Note this doesn't disable the warning, it only disables the choice of promoting it to an error that will force the compile to fail. Always review warnings.
You can also disable all warnings-as-errors with -Wno-error
. It's common to disable warnings-as-errors because it can be difficult to work with large bodies of code, often written by others and for less-strict compilers and language versions otherwise, as every warning would need to be satisfied before completing a build. And sometimes you want to build and run existing code without rewriting it to satisfy all the warnings.
Using `cout` to View Binary Data on Console
You seem to want to print the binary data in hexadecimal format. This can be done using the hex manipulator:
#include <iostream>
using namespace std;
// ...
int myVar = 0x1234;
cout << "0x" << hex << myVar; // 0x1234
Note that this only works for integers.
How to print binary number via printf
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
Convert integer to binary string with variable size
A straightforward way: Extract each bits using bitwise shift operation.
#include <iostream>
int main() {
int n = 3;
for (int i = 0; i < (1 << n); i++) {
for (int j = n - 1; j >= 0; j--) {
std::cout << ((i >> j) & 1);
}
std::cout << '\n';
}
return 0;
}
Note that this method will work only if n
is small enough not to cause an integer overflow (1 << n
doesn't exceed INT_MAX
).
To generate larger sequence, you can use recursion:
#include <iostream>
#include <string>
void printBits(int leftBits, const std::string& currentBits) {
if (leftBits <= 0) {
std::cout << currentBits << '\n';
} else {
printBits(leftBits - 1, currentBits + "0");
printBits(leftBits - 1, currentBits + "1");
}
}
int main() {
int n = 3;
printBits(n, "");
return 0;
}
Related Topics
Position of Least Significant Bit That Is Set
What Is the Correct Way of Using C++11'S Range-Based For
Where Is C Not a Subset of C++
Recommended Way to Initialize Srand
How to Pass a Member Function Where a Free Function Is Expected
Store Derived Class Objects in Base Class Variables
Adding External Library into Qt Creator Project
Is Returning by Rvalue Reference More Efficient
Variadic Template Pack Expansion
Why Is It Wrong to Use Std::Auto_Ptr≪≫ With Standard Containers
How to Handle Wrong Data Type Input
How to Print (Using Cout) a Number in Binary Form
Why Use Iterators Instead of Array Indices
Getting a File* from a Std::Fstream