typedef union byte_array { struct{byte byte1; byte byte2; byte byte3; byte byte4;}; struct{int int1; int int2;}; };byte_array |
...and access them by:
byte_array myarray; mybyte = myarray.byte1; myint = myarray.int1; |
typedef union byte_array { struct{byte byte1; byte byte2; byte byte3; byte byte4;}; struct{int int1; int int2;}; };byte_array |
byte_array myarray; mybyte = myarray.byte1; myint = myarray.int1; |
C# equivalent to C "union"?
cd12
http://winfx.msdn.microsoft.com/library/default.asp url=/library/en-us/dv_csref/html/163ab9b5-46f6-4d78-9025-f7bbba89b2e1.asp
For instance:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct ByteArray {
[FieldOffset(0)]
public byte Byte1;
[FieldOffset(1)]
public byte Byte2;
[FieldOffset(2)]
public byte Byte3;
[FieldOffset(3)]
public byte Byte4;
[FieldOffset(4)]
public byte Byte5;
[FieldOffset(5)]
public byte Byte6;
[FieldOffset(6)]
public byte Byte7;
[FieldOffset(7)]
public byte Byte8;
[FieldOffset(0)]
public int Int1;
[FieldOffset(4)]
public int Int2;
}
One thing to be careful of is the endian-ness of the machine if you plan to run it on non-x86 platforms that may have differing endianness. See http://en.wikipedia.org/wiki/Endianness for an explanation.
GlynP
bneacetp84
niezheng
public class U { short s; //================================================== public U(short s) { this.s = s;
}
//================================================== public byte AsByte(byte index) { const short maskLeft = 0xF0; const short maskRight = 0x0F; switch (index) { // index: 0..3 case 0: return (byte)((maskLeft & s) >> 4); // shift right 4 bits case 1: return (byte)(maskRight & s); default: return 0;}
}
}
Bill DiPierre
Gabriel Graves
Cheers
David
Ner1co
Thanks for the help!
So, to reference the "int1" above, would I do the following
myint = byte_array.int1
I will modify the structure for "short" instead of "int" since the other end of the USB link thinks ints are 16 bits...;)
Thanks again!
Balashanmugam
You may want to fix up FieldOffset for the Int2 field in your struct. It should be changed from 1 to 4.
Brenton House
V0rtex
Great minds think a like. Looks like we posted the same answer at the same time. ;)
kinpin9
You can actually do the following:
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct byte_array
{
[FieldOffset(0)]
public byte byte1;
[FieldOffset(1)]
public byte byte2;
[FieldOffset(2)]
public byte byte3;
[FieldOffset(3)]
public byte byte4;
[FieldOffset(0)]
public short int1;
[FieldOffset(2)]
public short int2;
}
However, you need to be careful as the 'int' datatype in the .NET Framework is actually a 32-bit integer not 16-bit. So 2 bytes actually make up 1 short.