3

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.

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Hasan A Yousef
  • 19,411
  • 21
  • 113
  • 174
  • 1
    Python also has first-class binary literals; you can write `0b101101111 + 0b111111` rather than have to convert them from strings, just as in Rust. – trent Apr 15 '20 at 19:15

1 Answers1

6

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 
Hasan A Yousef
  • 19,411
  • 21
  • 113
  • 174
  • 3
    [How do you set, clear and toggle a single bit in Rust?](https://stackoverflow.com/q/40467995/155423); [What is the bitwise NOT operator in Rust?](https://stackoverflow.com/q/38896155/155423). – Shepmaster Apr 15 '20 at 18:21