How to print the bits of a character in C#

2 Answers

0 votes
using System;
 
class Program
{
    static void print_bits(char ch) { 
        for (int i = 31; i >= 0; i--)
            Console.Write((ch >> i) & 1);
        Console.WriteLine();
    } 
     
    static void Main()
    {
        char ch = 'a';
         
        print_bits(ch);
    }
}
 
 
/*
run:
 
00000000000000000000000001100001
 
*/

 



answered Mar 6, 2019 by avibootz
0 votes
using System;

namespace CharacterBitsProgram
{
    internal static class Program
    {
        static void Main()
        {
            // Example usage.
            PrintCharacterBits('A');
            Console.WriteLine();

            PrintCharacterBits('a');
            Console.WriteLine();

            PrintCharacterBits('5');
        }

        /// <summary>
        /// Converts a character to its 8-bit binary representation.
        /// </summary>
        /// <param name="value">The character to convert.</param>
        /// <returns>A string containing the binary representation.</returns>
        private static string CharToBits(char value)
        {
            // Convert the character to its numeric Unicode value.
            int code = value;

            // Convert to binary and pad with leading zeros.
            return Convert.ToString(code, 2).PadLeft(8, '0');
        }

        /// <summary>
        /// Prints a character and its binary representation.
        /// </summary>
        /// <param name="value">The character to display.</param>
        private static void PrintCharacterBits(char value)
        {
            string bits = CharToBits(value);

            Console.WriteLine($"Character: '{value}'");
            Console.WriteLine($"Decimal  : {(int)value}");
            Console.WriteLine($"Binary   : {bits}");
        }
    }
}


/*
run:

Character: 'A'
Decimal  : 65
Binary   : 01000001

Character: 'a'
Decimal  : 97
Binary   : 01100001

Character: '5'
Decimal  : 53
Binary   : 00110101

*/

 



answered Oct 16 by avibootz
...