Convert integers/characters to their binary (text) representation (portable implementation)

tux4life 0 Tallied Votes 242 Views Share

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.

/* 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

A+++++ quality snippet would read this poster again.

MosaicFuneral 812 Nearly a Posting Virtuoso

Wait. bitset has an OR operator? Didn't realize that.

tux4life 2,072 Postaholic

>Wait. bitset has an OR operator? Didn't realize that.
Yes sure it has one, all the operators it supports are listed here:
http://www.cplusplus.com/reference/stl/bitset/operators/
(and bitwise OR-assignment is one of them :) )

MosaicFuneral 812 Nearly a Posting Virtuoso

Interesting. The only way I remember using bitset is in a template function, with bitset passed the value in its initializer.

By the way, you can use numeric_limits<T>::digits instead of sizeof()

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.