如何在 C# 中将 sbyte[] 转换为 byte[]? [英] How to convert a sbyte[] to byte[] in C#?

查看:39
本文介绍了如何在 C# 中将 sbyte[] 转换为 byte[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数来填充类型为 sbyte[] 的数组,我需要将此数组传递给另一个接受 byte[] 类型参数的函数.

I've got a function which fills an array of type sbyte[], and I need to pass this array to another function which accepts a parameter of type byte[].

我能否在不复制所有数据或使用 unsafe 魔法的情况下快速快速地转换它?

Can I convert it nicely and quickly, without copying all the data or using unsafe magic?

推荐答案

是的,你可以.由于 bytesbyte 具有相同的二进制表示,因此无需复制数据.只需对数组进行转换,然后将其转换为 byte[] 就足够了.

Yes, you can. Since both byte and sbyte have the same binary representation there's no need to copy the data. Just do a cast to Array, then cast it to byte[] and it'll be enough.

sbyte[] signed = { -2, -1, 0, 1, 2 };
byte[] unsigned = (byte[]) (Array)signed; 

这篇关于如何在 C# 中将 sbyte[] 转换为 byte[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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