How would I tell the compiler the number is binary?
ex how would I do this:
char a=01110101;
?
How would I tell the compiler the number is binary?
ex how would I do this:
char a=01110101;
?
why dont you go and try
(*Hint*You already know how ;P)
MSVC++~
This displays a 9 it should be a 3.
Code:char a=00000011; printf("%d",a);
int a; don't make a program without it.
I should not reply past 2 am...-_-
sry for bad info =/
MSVC++~
Maybe not what you are looking for but you could look into a bitset as a possibility
Outputs: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; }
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
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
You could also consider using a bitfield.
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.Code:struct bitfield_4_bits { unsigned int b1: 1; unsigned int b2: 1; unsigned int b3: 1; unsigned int b4: 1; };
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.