I have the two functions shown below which I built for serialisation of long and byte[] values.
public static byte[] LongToByte(long Value)
{
byte[] Output = new byte[8];
Output[0] = (byte)Value;
Output[1] = (byte)(Value >> 8);
Output[2] = (byte)(Value >> 16);
Output[3] = (byte)(Value >> 24);
Output[4] = (byte)(Value >> 32);
Output[5] = (byte)(Value >> 40);
Output[6] = (byte)(Value >> 48);
Output[7] = (byte)(Value >> 56);
return Output;
}
public static long LongFromByte(byte[] Value)
{
long Output = Value[0];
Output += ((long)Value[1] << 8);
Output += ((long)Value[2] << 16);
Output += ((long)Value[3] << 24);
Output += ((long)Value[4] << 32);
Output += ((long)Value[5] << 40);
Output += ((long)Value[6] << 48);
Output += ((long)Value[7] << 56);
return Output;
}
Will using the above methods ensure endianness remains the same across any platform which is using them.
Or will the result of either or change based on the endianness of the system processing the code?
Thanking all.
Yes it will because you’re extracting each byte individually and storing it in the array. So ‘Output[0]’, for example, is always the lowest 8 bits of the number you’re converting. If you then write the array (to a disk file or across some transport), the bytes will always be in the order that you specified.
Alternately, you might consider using the technique described in the remarks section of the BitConverter class documentation.