如何在&[u8]中编写u32?

Wer*_*rem 2 casting rust

我正在尝试渲染图像。我编写了一个put_pixel函数,将RGBA像素写入代表图像的数组中。

图像是保存i8值的一维数组(每个字节都是颜色的组成部分)。我想一步写颜色。

fn put_pixel(x: u16, y: u16, color: u32, width: u16, height: u16, buffer: &[u8]) {
    let index = 0; // I'll calculate the right index later.
    buffer[index] as u32 = color; // I want to write the color here.
}
Run Code Online (Sandbox Code Playgroud)

所以,这给了我一个错误,说

fn put_pixel(x: u16, y: u16, color: u32, width: u16, height: u16, buffer: &[u8]) {
    let index = 0; // I'll calculate the right index later.
    buffer[index] as u32 = color; // I want to write the color here.
}
Run Code Online (Sandbox Code Playgroud)

听起来很合逻辑,但我不知道如何将像素“投射”到阵列中。

orc*_*rcy 6

从 Rust 1.32 开始,现在有了u32::to_be_bytes(self) -> [u8; 4]. be名称为“big-endian”,还有ne(native)和le(little-endian)。


E_n*_*ate 5

听起来很合逻辑,但我不知道如何将像素“投射”到阵列中。

将的引用转换为的引用是不安全u8u32。如果编译器让你指定类型的值u32u8,它可能已经没有工作,你打算,因为该值将不得不被截断成单个组件,以便它适合在一个单一片元素。

话虽如此,通常byteorder用于从切片或其他二进制数据流中读取和写入此类类型。

use byteorder::{LittleEndian, WriteBytesExt};

fn put_pixel(x: u16, y: u16, color: u32, width: u16, height: u16, buffer: &mut [u8]) {
    let index = unimplemented!();
    buffer[index..].write_u32::<LittleEndian>(color).unwrap();
}
Run Code Online (Sandbox Code Playgroud)