0

I am able to replace the value with 1 but it is not replacing with 0. Output of below program is 0b11111111 . Ideally it should be 0b11110000. Please let me know what I am missing here.

use std::mem;

fn main() {
    let a: u8 = 0b00001111;
    let b: u8 = 0b11111111;
    let c: u8 = 0b00000000;
    let length = mem::size_of_val(&a) * 8;
    let mut p : u8 = b;

    for n in 0..length {


        if (a >> n & 1) == 0b1 {
            let d = c >> n & 1;
            p = p | (d << n);
        }

    }

    println!("0b{:08b}", p);

}

Ayush Mishra
  • 567
  • 1
  • 7
  • 19

1 Answers1

3

This isn't specific to rust.

True | x => True
True & x => x
True ^ x =? ¬x
False | x => x
False & x => False
False ^ x => x

So for your values

a | b == 0b11111111
a ^ b == 0b11110000
a & b == 0b00001111

In terms of your code, you're not doing anything in the case where a >> n & 1 == 0. You need to use something like

let d = b ^ (1<<n); // switch nth bit - gives something like 0b11101111
p = p & d; // leaves all bits untouched except nth which is set to 0
Holloway
  • 6,412
  • 1
  • 26
  • 33