如何将无符号整数的一部分转换为相同大小的有符号整数? [英] How do I cast a slice of unsigned integers to signed integers of the same size?

查看:46
本文介绍了如何将无符号整数的一部分转换为相同大小的有符号整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前的最大努力是

// `value` is a `&[u8]`
let v = unsafe { slice::from_raw_parts(value.as_ptr() as *const i8, value.len()) };

为此,需要 unsafe 似乎有点过头了.我希望这是零成本.

It seems overkill to need unsafe for this. I'd like this to be zero cost.

推荐答案

您的代码已经是零成本了.但是它必须在下面使用不安全的代码,因为当通过 slice :: from_parts mem :: transmute 完成时,编译器不能保证所有类型的切片转换都是安全的.无论哪种安全"功能在这里都适用,可能会在确保项目类型与此转换兼容(即相同的大小和内存对齐)的同时将其括起来.

Your code is as zero cost as it can be already. But it has to use unsafe code underneath because not all kinds of slice conversions are guaranteed to be safe by the compiler when done through slice::from_parts or mem::transmute. Whichever "safe" function is suitable here would likely enclose that while ensuring that the item types are compatible with this conversion (i.e. same size and memory alignment).

您也许可以找到多个包装箱,以便对该转换进行适当的测试和维护.箱子 安全传输 实现此转换,同时支持更多绑定警卫和对齐检查(免责声明:我是合作者之一).

You may be able to find multiple crates which proper testing and maintenance for this conversion. The crate safe-transmute implements this conversion, while supporting more bound guards and alignment checks (disclaimer: I'm one of the collaborators).

use safe_transmute::transmute_many_pedantic;

let value: &[u8] = &[0x00, 0x01, 0x12, 0x24, 0x00];
let words: &[i8] = transmute_many_pedantic(values)?;

这篇关于如何将无符号整数的一部分转换为相同大小的有符号整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆