C# 从 uint[] 转换为 byte[]
这可能是一个简单的方法,但我似乎找不到一种简单的方法来做到这一点。我需要将 84 uint 数组保存到 SQL 数据库的 BINARY 字段中。因此,我在 C# ASP.NET 项目中使用以下几行:
//This is what I have
uint[] uintArray;
//I need to convert from uint[] to byte[]
byte[] byteArray = ???
cmd.Parameters.Add("@myBindaryData", SqlDbType.Binary).Value = byteArray;
那么如何从 uint[] 转换为 byte[]?
This might be a simple one, but I can't seem to find an easy way to do it. I need to save an array of 84 uint's into an SQL database's BINARY field. So I'm using the following lines in my C# ASP.NET project:
//This is what I have
uint[] uintArray;
//I need to convert from uint[] to byte[]
byte[] byteArray = ???
cmd.Parameters.Add("@myBindaryData", SqlDbType.Binary).Value = byteArray;
So how do you convert from uint[] to byte[]?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
怎么样:
这会以小端格式做你想做的事......
How about:
This'll do what you want, in little-endian format...
您可以使用 System.Buffer.BlockCopy 来执行此操作:
http:// /msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx
这比使用 for 循环或某些类似的构造要高效得多。它直接将字节从第一个数组复制到第二个数组。
要转换回来,只需反向执行相同的操作即可。
You can use System.Buffer.BlockCopy to do this:
http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx
This will be much more efficient than using a for loop or some similar construct. It directly copies the bytes from the first array to the second.
To convert back just do the same thing in reverse.
没有内置的转换函数可以执行此操作。由于数组的工作方式,需要分配一个全新的数组并填充其值。您可能只需要自己编写即可。您可以使用byte[] 中。
System.BitConverter.GetBytes(uint)
函数完成一些工作,然后将结果值复制到最终的这是一个将以小端格式进行转换的函数:
There is no built-in conversion function to do this. Because of the way arrays work, a whole new array will need to be allocated and its values filled-in. You will probably just have to write that yourself. You can use the
System.BitConverter.GetBytes(uint)
function to do some of the work, and then copy the resulting values into the finalbyte[]
.Here's a function that will do the conversion in little-endian format:
听取@liho1eye 的建议,确保您的 uint 真正适合字节,否则您将丢失数据。
Heed advice from @liho1eye, make sure your uints really fit into bytes, otherwise you're losing data.
如果您需要每个 uint 的所有位,则必须创建一个适当大小的 byte[] 并将每个 uint 复制到它表示的四个字节中。
像这样的东西应该有效:
If you need all the bits from each uint, you're gonna to have to make an appropriately sized byte[] and copy each uint into the four bytes it represents.
Something like this ought to work: