I have a struct definition in c# as follows
public struct test { byte SetCommonPOP; byte SetCommonSVP; byte SetCommonUHDP; byte SetCommonMHDP; }; How do I assign an int y to an object x of this structure without having to use unsafe?
You could write a custom conversion operator:
public struct Test { private readonly byte pop; private readonly byte svp; private readonly byte uhdp; private readonly byte mhdp; // TODO: Properties to return the above public Test(byte pop, byte svp, byte uhdp, byte mhdp) { this.pop = pop; this.svp = svp; this.uhdp = uhdp; this.mhdp = mhdp; } public static implicit operator Test(int value) { // Working from most significant to least significant bits... byte mhdp = (byte) ((value >> 0) & 0xff); byte uhdp = (byte) ((value >> 8) & 0xff); byte svp = (byte) ((value >> 16) & 0xff); byte pop = (byte) ((value >> 24) & 0xff); return new Test(pop, svp, uhdp, mhdp); } } Personally I'd prefer a static FromInt32 method instead of an implicit operator, but that's your call. It's very possible that you don't need all the & 0xff parts in the conversion - and I wouldn't bother with them if you were using a uint instead of an int. Extracting parts of a signed integer just makes me twitchy, and this is possibly overcompensation. Another alternative would be a cast of value to a uint as a local variable to start with.
Another option is to use an explicit struct layout:
[StructLayout(LayoutKind.Explicit)] public struct Test { [FieldOffset(3)] public readonly byte pop; [FieldOffset(2)] public readonly byte svp; [FieldOffset(1)] public readonly byte uhdp; [FieldOffset(0)] public readonly byte mhdp; [FieldOffset(0)] private int value; public static Test FromInt32(int value) { var test = new Test(); test.value = value; return test; } }
intto be interpreted? Different endianness systems could convert in different ways.