當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Rust usize.from_ne_bytes用法及代碼示例

本文簡要介紹rust語言中 usize.from_ne_bytes 的用法。

用法

pub const fn from_ne_bytes(bytes: [u8; 8]) -> usize

從其內存表示創建一個本地字節序整數值作為本地字節序的字節數組。

由於使用了目標平台的本機字節順序,可移植代碼可能希望使用 from_be_bytes from_le_bytes ,視情況而定。

注意:該函數采用長度為 2、4 或 8 字節的數組,具體取決於目標指針的大小。

例子

let value = usize::from_ne_bytes(if cfg!(target_endian = "big") {
    [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]
} else {
    [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]
});
assert_eq!(value, 0x1234567890123456);

從切片而不是數組開始時,可以使用易出錯的轉換 API:

use std::convert::TryInto;

fn read_ne_usize(input: &mut &[u8]) -> usize {
    let (int_bytes, rest) = input.split_at(std::mem::size_of::<usize>());
    *input = rest;
    usize::from_ne_bytes(int_bytes.try_into().unwrap())
}

相關用法


注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 usize.from_ne_bytes。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。