C#数组如何存储在内存中 [英] C# How are arrays stored in memory

查看:532
本文介绍了C#数组如何存储在内存中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的主要问题是,只要不重新初始化(新字节[#])作为参数传递的数组,这将始终有效吗?

I guess my main question is, will this always work as long as I don't re-initialize (new byte[#]) the array that was passed as the parameter?

static unsafe decimal GetDecimal(byte[] ba)
{
    decimal* decimal_PTR;
    fixed (byte* byte_PTR = &ba[0])
    {
        decimal_PTR = ((decimal*)byte_PTR);
    }
    return *decimal_PTR;
}

我不确定C#如何处理内存中的数组.直到大约一个小时前,我什至不知道它们是托管类型.我只想知道我是否将十进制数作为byte []传递,它将始终返回正确的值吗?您可以提供的任何其他信息都将受到赞赏.

I'm not sure how C# handles arrays in memory. I didn't even know they were managed types until about an hour ago. I just want to know if I pass in a decimal as a byte[], will it always return the correct value? Any other information you can provide is appreciated.

推荐答案

在@MJLaukala通过注释进行澄清之后:

After @MJLaukala's clarification through comments:

  1. .Net中的数组就像其他任何语言一样,是一块连续的内存.但是与C/C ++不同,此块不仅存储数组的元素,还存储其他信息",包括数组的等级和长度.话虽如此,& ba [0]将把指针返回到数组的第一个元素,您可以放心地将指针增加到最后一个元素. ba.Length将提供数组中元素的数量.

  1. An Array in .Net is a block of contiguous memory just like any other language. But unlike C/C++ this block not only stores the array's elements but also other 'information' including rank and length of the array. Having said this, &ba[0] will return the pointer to the first element of the array and you can safely increment the pointer to go till the last element. ba.Length will provide the number of elements in the array.

现在,如果您确定字节数组恰好代表小数,那么您的代码将可以正常工作.

Now if you are sure that the byte array represents the decimal exactly then your code will work fine.

小数点(128位)的内存布局:

Memory layout of decimal (128 bits):

前2个字节为0

第3个字节包含一个介于0到28之间的值,表示将96位整数部分除以产生小数值的幂10.

3rd byte contain a value between 0 and 28, indicating the power of 10 to divide the 96-bit integer part by to produce the Decimal value

第4个字节:前7位为零,第8位表示小数点的符号(1表示负数)

4th byte : first 7 bits are zero, 8th bit indicates the sign of the decimal (1 meaning negative)

接下来的12个字节:小数的整数部分.

Next 12 bytes: Integer part of the Decimal.

这篇关于C#数组如何存储在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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