How to extract higher and lower 32 bits from 64 bits?

Hi,

I want to extract 32 bits from 64 bits on my no-std, embedded code. So to test, tried the following logic on x86 to test.

fn main() {
	let v: u64 = 0x1234_5678_9abc_def0;
	let hi32: u32 = (v & 0xFFFF_FFFF_0000_0000) >> 32;
	println!(" hi32 is {}", hi32);
}

It threw the error and gave the help to fix.

let hi32: u32 = (v & 0xFFFF_FFFF_0000_0000) >> 32;
expected u32, found u64
** expected due to this**
help: you can convert a u64 to a u32 and panic if the converted value doesn't fit
** |**
7 | let hi32: u32 = ((v & 0xFFFF_FFFF_0000_0000) >> 32).try_into().unwrap();
| + +++++++++++++++++++++

Then tried to fix the with the help

use std::convert::TryInto;
fn main() {
	let v: u64 = 0x1234_5678_9abc_def0;
        let hi32: u32 = ((v & 0xFFFF_FFFF_0000_0000) >> 32).try_into().unwrap();
	println!(" hi32 is {:2x}", hi32);
}

Result:
hi32 is 12345678 => It worked

Now, on my embedded code, I dont have std lib. So how to achieve extracting higher and lower 32 bits out of 64 bit value in no-std environment.

1 Like

just cast it directly with as keyword (btw, you don't need the bit mask operation, integer cast to smaller type will truncate automatically):

let hi32 = (v >> 32) as u32;
let lo32 = v as u32;
4 Likes

the document about numeric cast is:

https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast

TryInto is available in core, so you can still use it (but as is a reasonable choice here too, since it obviously can't overflow).

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.