How to print the bits of a character in Rust

3 Answers

0 votes
/// Converts a character to its 8-bit binary representation.
///
/// Note:
/// This function assumes the character fits into one byte (ASCII).
/// For full Unicode support, see the Unicode example below.
fn char_to_bits(ch: char) -> String {
    let value: u8 = ch as u8;

    format!("{:08b}", value)
}

/// Prints a character and its binary representation.
fn print_character_bits(ch: char) {
    println!("Character: '{ch}'");
    println!("Decimal  : {}", ch as u32);
    println!("Binary   : {}", char_to_bits(ch));
}

fn main() {
    // Usage examples

    print_character_bits('A');
    println!();

    print_character_bits('a');
    println!();

    print_character_bits('5');
    println!();

    print_character_bits('@');
}


/*
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
0 votes
/// Converts a Unicode character to a 32-bit binary string.
fn unicode_char_to_bits(ch: char) -> String {
    format!("{:032b}", ch as u32)
}

fn main() {
    // Usage examples

    println!("{}", unicode_char_to_bits('A'));
    println!("{}", unicode_char_to_bits('é'));
}


/*
run:

00000000000000000000000001000001
00000000000000000000000011101001

*/

 



answered Oct 16 by avibootz
edited Oct 16 by avibootz
0 votes
/// Converts a character to its 8-bit binary representation.

fn char_to_bits(ch: char) -> String {
    format!("{:08b}", ch as u8)
}

fn main() {
    // Usage examples

    println!("{}", char_to_bits('A'));
    println!("{}", char_to_bits('1'));
}


/*
run:

01000001
00110001

*/

 



answered Oct 16 by avibootz
...