# Thread: binary in C++

1. ## binary in C++

How would I tell the compiler the number is binary?
ex how would I do this:
char a=01110101;
?

2. why dont you go and try

(*Hint*You already know how ;P)

3. This displays a 9 it should be a 3.
Code:
char a=00000011;
printf("%d",a);

4. I should not reply past 2 am...-_-

sry for bad info =/

5. Maybe not what you are looking for but you could look into a bitset as a possibility
Code:
#include <iostream>
#include <bitset>
#include <string>
using namespace std;

int main()
{
bitset<8> bits1;
bitset<8> bits2(string("101"));  // One way of initializing a bitset
cout << "Enter in a value in binary (max 8 bits): ";
cin >> bits1;                    // Other way of initializing a bitset
cout << "The binary value " << bits1 << " is equal to " << bits1.to_ulong() << endl;
cout << "The binary value " << bits2 << " is equal to " << bits2.to_ulong() << endl;
return 0;
}
Outputs:
Enter in a value in binary (max 8 bits): 0011
The binary value 00000011 is equal to 3
The binary value 00000101 is equal to 5

6. You could also consider using a bitfield.

Code:
struct bitfield_4_bits
{
unsigned int b1: 1;
unsigned int b2: 1;
unsigned int b3: 1;
unsigned int b4: 1;
};
Each member is a single bit, accessing the bits can be done the same way as with normal structures. Cconversion from and to a char you can be done using structure mapping.

7. ## Don't try to use binary in your source code.

In your sample line, you are using 01110101 as a constant. In this case it's usually best to do the conversion "manually" and use hex (0x75) in your source code. (Sometimes I'll put the binary value in a comment.) When you get beyond 8 bits, hex is easier (for humans) to read than binary anyway.

As you may know, all numbers are stored in memory in binary. So, the number-base that you use in the source code is for your convenience only. Any "conversion" is only done during input, output, or compilation.

If you haven't learned to convert binary to hex yet, Windows has a handy calculator: Start->Programs->Accessories->Calculator [View] [Scientific] [Hex]

When I want to display a number in binary, I use bitset.

To get binary input from the user, I input the number as a string, then use strtoul() to convert it to a number.

Popular pages Recent additions