lupinx2
lupinx2

Reputation: 113

How do I convert an integer to binary in Rust, such that i can iterate over the digits?

I am trying to convert a decimal i32 in Rust to a binary representation I can manipulate, I understand from this question that I can print and declare i32 values to and from binary format; but I'm trying implement binary division using logical operators, (as opposed to just using the standard i32 math operators, this is for a leetcode question) and I'm not familiar enough with Rust syntax to understand how I can do this with the Binary trait that i32 implements, or if there is perhaps a dedicated binary type or iterator that I should be using.

While writing this question, I was able to figure out a workable solution by using the String type like so:

fn main() {
    let a : i32 = 5;
    let bin_a = String::from(format!("{a:b}"));
    let bin_s = String::from("101");

    assert_eq!(bin_a, bin_s);
}

But this feels clunky and like there's probably a more direct way of iterating over binary representations of numbers, so I'll submit this question in hopes someone more knowledgeable can contribute; thanks in advance for any help.

Upvotes: 5

Views: 7000

Answers (1)

Jmb
Jmb

Reputation: 23319

Basic operations:

  • (x >> n) & 1 gives you the nth bit,
  • x & !(1 << n) clears the nth bit,
  • and x | (1 << n) sets the nth bit.

So iterating over the digits is as simple as (0..32).map (|n| (x >> n) & 1) from least to most significant, or (0..32).rev().map (|n| (x >> n) & 1) from most to least significant.

Upvotes: 10

Related Questions