This is a portable implementation for converting a character or an integer to its binary text equivalent.
It makes use of the CHAR_BIT constant (which is defined in the header file climits) to get the number of bits a byte consists of on the implementation where you compile this code on.
Further for simplicity, it makes use of STL: bitset :)
To understand how the program works, I advise you to just compile and run it.
When you run the program, it will ask you to enter a character
(or an integer, in case you're running the integer converter).
After you've pressed the ENTER key, the program will display the corresponding binary value.
I've also supplied some sample output, in case you're not be able to compile the code directly, you could take a look at that first.
Convert integers/characters to their binary (text) representation (portable implementation)
/* Character to binary */
#include <iostream>
#include <bitset>
#include <climits>
int main()
{
std::bitset<CHAR_BIT> byte;
char ch;
std::cout << "Enter a character: ";
std::cin >> ch;
byte |= ch;
std::cout << "Binary representation: " << byte << std::endl;
}
/*
My output
Enter a character: a
Binary representation: 01100001
*/
/* Integer to binary */
#include <iostream>
#include <bitset>
#include <climits>
int main()
{
std::bitset<CHAR_BIT * sizeof(int)> binary;
int i;
std::cout << "Enter an integer: ";
std::cin >> i;
binary |= i;
std::cout << "Binary representation: " << binary << std::endl;
}
/*
My output:
Enter an integer: 59
Binary representation: 00000000000000000000000000111011
*/
jephthah 1,888 Posting Maven
MosaicFuneral 812 Nearly a Posting Virtuoso
tux4life 2,072 Postaholic
MosaicFuneral 812 Nearly a Posting Virtuoso
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.