Reputation: 171
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;
}
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.
Upvotes: 2
Views: 5616
Reputation: 2736
After @MJLaukala's clarification through comments:
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.
Memory layout of decimal (128 bits):
First 2 bytes are 0
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
4th byte : first 7 bits are zero, 8th bit indicates the sign of the decimal (1 meaning negative)
Next 12 bytes: Integer part of the Decimal.
Upvotes: 3