Hasan A Yousef
Hasan A Yousef

Reputation: 24948

How do I manipulate binary numbers in Rust?

How can I handle and do mathematical operations in Rust, such as adding or dividing two binary numbers?

In Python, there is something like this:

bin(int('101101111', 2) + int('111111', 2))

Which works fine unless you need to use floating point numbers.

Upvotes: 8

Views: 11751

Answers (1)

Hasan A Yousef
Hasan A Yousef

Reputation: 24948

Binary numbers in Rust can be defined using the prefix 0b, similar to the 0o and 0x prefixes for octal and hexadecimal numbers.

To print them, you can use the {:b} formatter.

fn main() {
    let x = 0b101101111;
    let y = 0b111111;
    println!("x + y = {:b} that is {} + {} = {} ", x + y, x, y, x + y);

    let a = 0b1000000001;
    let b = 0b111111111;
    println!("a - b = {:b} that is {} - {} = {} ", a - b, a, b, a - b);

    let c = 0b1000000001;
    let d = 0b111111111;
    println!("c * d = {:b} that is {} * {} = {} ", c * d, c, d, c * d);

    let h = 0b10110101101;
    let r = 0b101;
    println!("h / r = {:b} that is {} / {} = {} ", h / r, h, r, h / r);
    println!("h % r = {:b} that is {} % {} = {} ", h % r, h, r, h % r);
}

The output is:

x + y = 110101110 that is 367 + 63 = 430 
a - b = 10 that is 513 - 511 = 2 
c * d = 111111111111111111 that is 513 * 511 = 262143 
h / r = 100100010 that is 1453 / 5 = 290 
h % r = 11 that is 1453 % 5 = 3 

Upvotes: 14

Related Questions