Skip to content

Instantly share code, notes, and snippets.

@ochaloup
Last active June 6, 2024 11:42
Show Gist options
  • Save ochaloup/82062ecb6b479a9dbc8b142a2cc2ad5c to your computer and use it in GitHub Desktop.
Save ochaloup/82062ecb6b479a9dbc8b142a2cc2ad5c to your computer and use it in GitHub Desktop.
Shifting with bytes bits in Rust
fn main() {
let data: &mut [u8] = &mut [0, 0, 0, 0]; // your byte slice
let index: usize = 2; // the position where you want to write the byte
let byte: u8 = 42; // the byte you want to write; 42 =>
// Write the byte to the specified position in the byte slice
data[index] = byte;
print_byte(&byte);
// switching first bit to 1
let new_byte = byte | 1 << 0;
print_byte(&new_byte);
println!("All bytes: {}", format_bytes(data));
}
// fn bits(byte: &u8) -> [u8;8] {
// let mut bits = [0_u8;8];
// for i in 0..8 {
// let mask = 1 << i;
// let bit_is_set = (mask & byte) > 0;
// bits[i] = if bit_is_set {
// 1
// } else {
// 0
// };
// }
// bits
// }
fn format_to_bits(byte: &u8) -> String {
let mut bits = [0_u8; 8];
for i in 0..8 {
let mask = 1 << i;
let bit_is_set = (mask & byte) > 0;
bits[i] = if bit_is_set { 1 } else { 0 };
}
bits.iter().map(|b| b.to_string()).collect()
}
fn format_bytes(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:08b},", b)).collect()
}
fn print_byte(byte: &u8) {
println!("byte {} in bits {:?}", byte, format_to_bits(byte));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment