当前位置: 首页 > 工具软件 > a2u > 使用案例 >

c语言 u16 u8 转换,如何将两个u8原语转换为u16原语?

隆礼骞
2023-12-01

如果你实际上有两个不同的u8,传统的解决方案涉及按位操作,特别是移位和按位OR。这需要零堆分配并且非常有效:

let number = ((vector[0] as u16) << 8) | vector[1] as u16;

图解说明:

A0 B0

+--------+ +--------+

|XXXXXXXX| |YYYYYYYY|

+-------++ +-------++

| |

A1 = A0 as u16 | B1 = B0 as u16 |

+---------------v+ +---------------v+

|00000000XXXXXXXX| |00000000YYYYYYYY|

+---------------++ +---------------++

| |

A2 = A1 << 8 | |

+---------------v+ |

|XXXXXXXX00000000| |

+---------------++ |

| +--+ |

+-------------->OR

+-++

|

V = A2 | B1 |

+----------+----v+

|XXXXXXXXYYYYYYYY|

+----------------+

然而,你真的在​​狭隘地看待你的问题。您没有两个u8,而是&[u8]。

extern crate byteorder;

use byteorder::{ByteOrder, LittleEndian};

fn main() {

let data = [1, 16];

let v = LittleEndian::read_u16(&data);

println!("{}", v);

}

当你想通过缓冲区处理读取时,它显示了它的强大功能:

extern crate byteorder;

use byteorder::{BigEndian, LittleEndian, ReadBytesExt};

fn main() {

let data = [1, 16, 1, 2];

let mut current = &data[..];

let v1 = current.read_u16::();

let v2 = current.read_u16::();

println!("{:?}, {:?}", v1, v2); // Ok(4097), Ok(258)

}

如您所见,您需要了解输入数据的endianness。

另见:

原始帖子的免费代码审核:

此处无需使用to_vec,请改用vec!。

无需指定绝大多数类型。

let vector = [1u8, 16].to_vec();

let vector0 = format!("{:02x}", vector[0]);

let vector1 = format!("{:02x}", vector[1]);

let mut vector_combined = String::new();

vector_combined = vector_combined + &vector0.clone();

vector_combined = vector_combined + &vector1.clone();

let number = u16::from_str_radix(&vector_combined.to_string(), 16).unwrap();

在添加时,无需克隆字符串,然后再引用它们。

无需将String转换为String中的另一个from_str_radix。

let vector0 = format!("{:02x}", vector[0]);

let vector1 = format!("{:02x}", vector[1]);

let mut vector_combined = String::new();

vector_combined = vector_combined + &vector0;

vector_combined = vector_combined + &vector1;

let number = u16::from_str_radix(&vector_combined, 16).unwrap();

无需创建要追加的空String,只需使用vector0

let vector0 = format!("{:02x}", vector[0]);

let vector1 = format!("{:02x}", vector[1]);

let vector_combined = vector0 + &vector1;

let number = u16::from_str_radix(&vector_combined, 16).unwrap();

根本不需要创建两个字符串,一个可以:

let vector_combined = format!("{:02x}{:02x}", vector[0], vector[1]);

let number = u16::from_str_radix(&vector_combined, 16).unwrap();

当然,这仍然不是正确的解决方案,但它更好。

 类似资料: