Function bit_cast

Source
pub fn bit_cast<const M: usize, const N: usize>(x: Bits<N>) -> Bits<M>
Expand description

Cast from one bit width to another with truncation or zero padding The bit_cast function allows you to convert from one bit width to another. It handles the different widths in the following simplified manner: - if casting to a narrower bit width, the most significant bits are discarded until the new value fits into the specified bits - if casting to a wider bit width, the most significant bits are padded with zeros until the new value occupies the specified bits This may seem a bit counterintuitive, but it fits logical circuitry behavior. Narrowing is usually done by preserving the least significant bits (so that the carry bits are discarded when adding, for example). Widening is also usually done (for unsigned values) by zero extending the most significant bits. The bit_cast operation does both of these operations depending on the arguments.

First, an example of widening, in this case, an extra nibble is added to the most significant bits, and is set to zero.

 let x : Bits<12> = bits(0xEAF);
 let y : Bits<16> = bit_cast(x); // M = 16, N = 12
 assert_eq!(y, bits::<16>(0x0EAF));

In the second example, we downcast, this time, discarding the most significant nibble.

let x : Bits<16> = bits(0xDEAF);
let y : Bits<12> = bit_cast(x); // M = 12, N = 16
assert_eq!(y, bits::<12>(0xEAF));

Note that internally, you can bit_cast from an arbitrary bit length to another arbitrary bit length without losing information because of any internal Rust limit.

Note also that bit-casting does not preserve signedness. Generally, RustHDL follows hardware conventions that values are unsigned. If you want to work with signed bit vectors, use [Signed] instead.