How to print the bits of a character in C++

2 Answers

0 votes
#include <iostream> 
 
void print_bits(char ch, int len) { 
   for (int i = len - 1; i >= 0; i--)
        std::cout << ((ch >> i) & 1);
} 
    
int main() 
{ 
    char ch = 'a';
      
    print_bits(ch, 8);
} 
 
 
/*
run:
 
01100001

*/

 



answered Mar 6, 2019 by avibootz
edited Oct 16 by avibootz
0 votes
#include <iostream>
#include <string>
#include <bitset>

/**
 * Converts a character to its 8-bit binary representation.
 *
 * @param ch The character to convert.
 * @return A string containing the 8-bit binary representation.
 */
std::string charToBits(char ch)
{
    // Convert to unsigned char to avoid issues with signed chars.
    unsigned char value = static_cast<unsigned char>(ch);

    return std::bitset<8>(value).to_string();
}

/**
 * Prints a character and its binary representation.
 *
 * @param ch The character to display.
 */
void printCharacterBits(char ch)
{
    std::cout << "Character: '" << ch << "'\n"
              << "Decimal  : " << static_cast<int>(static_cast<unsigned char>(ch)) << '\n'
              << "Binary   : " << charToBits(ch) << '\n';
}

int main()
{
    // Usage examples
    printCharacterBits('A');
    std::cout << '\n';

    printCharacterBits('a');
    std::cout << '\n';

    printCharacterBits('5');
    std::cout << '\n';

    printCharacterBits('@');
}



/*
run:

Character: 'A'
Decimal  : 65
Binary   : 01000001

Character: 'a'
Decimal  : 97
Binary   : 01100001

Character: '5'
Decimal  : 53
Binary   : 00110101

Character: '@'
Decimal  : 64
Binary   : 01000000

*/

 



answered Oct 16 by avibootz
...