Shintos
Shintos

Reputation: 41

C++ Unions in C#, how do they work underneath?

i have implemented c++ unions in c#, just to verify that i´m understandig it. But it seems that i understand nothing. I expected some times a completly different output. My Code:

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication2
{
[StructLayout(LayoutKind.Explicit)]
class union
{
    [FieldOffset(0)]
    public double d;
    [FieldOffset(0)]
    public float f0;
    [FieldOffset(4)]
    public float f1;
    [FieldOffset(0)]
    public int i0;
    [FieldOffset(4)]
    public int i1;
    [FieldOffset(0)]
    public short s0;
    [FieldOffset(2)]
    public short s1;
    [FieldOffset(4)]
    public short s2;
    [FieldOffset(6)]
    public short s3;

}

class Program
{
    static void Main(string[] args)
    {
        union su = new union();
        su.f0 = 19.012012F;
        su.f1 = 3.14159265F;
        Console.WriteLine(su.d);
        Console.WriteLine(su.i0);
        Console.WriteLine(su.i1);
        Console.WriteLine(su.s0);
        Console.WriteLine(su.s1);
        Console.WriteLine(su.s2);
        Console.WriteLine(su.s3);
        Console.ReadLine();
    }
}
} 

And my output is:

For example, i thought s0 would be 30209 and not 6298. Can someone explain how it works?

Upvotes: 3

Views: 159

Answers (2)

Shintos
Shintos

Reputation: 41

Stupid me, has known the answer, but was unable to do basic math. It is really simple. Translate your float in IEEE 754. And then check your offset(in bytes), that is your starting point. Make sure you know the length of your type in bit or better in byte. Then resolve your number like you have learnt before.
For Example:
The last 16 bit(fraction) of f0 are: 0001 1000 (Byte 1) 1001 1010(Byte 0)
s0 is a short integer so it size is 16-Bit or 2 Bytes. Now starting to resolve s0 by starting at the LSB to:
2 + 8 + 16 + 128 + 2048 + 4096 = 6298

So nothing special here.
I´m truly sorry for the inconvenience.

Upvotes: 1

NonStatic
NonStatic

Reputation: 1081

I think you may need to use struct other than class. Here is something more: Discriminated union in C#

Upvotes: 0

Related Questions