We can do this by asking C# to make us a struct that shares memory space for its members:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct Bynteger{
[FieldOffset(0)]
public byte Lowest;
[FieldOffset(1)]
public byte Middle;
[FieldOffset(2)]
public byte OtherMiddle;
[FieldOffset(3)]
public byte Highest;
[FieldOffset(0)]
public int Int;
[FieldOffset(0)]
public uint UInt;
}
If you assign to those bytes then read the int
or the uint
you'll get the value:
var b = new Bynteger{
Lowest = 0xAA,
Middle = 0xBB,
OtherMiddle = 0xCC,
Highest = 0xDD
};
Console.WriteLine(b.Int); //prints -573785174
Console.WriteLine(b.UInt); //prints 3721182122
Console.WriteLine(b.UInt.ToString("X")); //prints 0xDDCCBBAA
how can we obtain: 0xDDAABBCC ?
Er.. If 0xDD AA BB CC
isn't a typo (did you mean to say 0xDD CCBBAA`?), you can jiggle the layout around by changing the number in the FieldOffset, e.g.:
[FieldOffset(2)]
public byte Lowest;
[FieldOffset(1)]
public byte Middle;
[FieldOffset(0)]
public byte OtherMiddle;
[FieldOffset(3)]
public byte Highest;
Will give you the 0xDDAABBCC you requested, if you keep the assignments you said (Lowest = 0xAA etc)
You're free to name the fields however you like too.. (perhaps B1 to B4 ?)