// /** // * File: ByteArrayExtensions.cs // * Author: haraldwolff // * // * This file and it's content is copyrighted by the Author and / or copyright holder. // * Any use wihtout proper permission is illegal and may lead to legal actions. // * // * // **/ using System; namespace ln.type { public enum Endianess { BIG, LITTLE } public static class ByteArrayExtensions { public static byte[] To(this byte[] bytes,Endianess endianess) { if (BitConverter.IsLittleEndian == (endianess==Endianess.BIG)) Array.Reverse(bytes); return bytes; } public static byte GetByte(this byte[] bytes, ref int offset) => bytes[offset++]; public static byte[] GetByte(this byte[] bytes,ref int offset,out byte value) { value = GetByte(bytes, ref offset); return bytes; } public static byte[] GetShort(this byte[] bytes, ref int offset, out short value) => GetShort(bytes, ref offset, out value, Endianess.LITTLE); public static byte[] GetShort(this byte[] bytes, ref int offset, out short value, Endianess endianess) { value = GetShort(bytes, ref offset, endianess); return bytes; } public static short GetShort(this byte[] bytes, ref int offset, Endianess endianess) => BitConverter.ToInt16(bytes.Slice(ref offset, 2).To(endianess), 0); public static byte[] GetUShort(this byte[] bytes, ref int offset, out ushort value) => GetUShort(bytes, ref offset, out value, Endianess.LITTLE); public static byte[] GetUShort(this byte[] bytes, ref int offset, out ushort value, Endianess endianess) { value = GetUShort(bytes, ref offset, endianess); return bytes; } public static ushort GetUShort(this byte[] bytes, ref int offset, Endianess endianess) => BitConverter.ToUInt16(bytes.Slice(ref offset, 2).To(endianess), 0); public static byte[] GetInt(this byte[] bytes, ref int offset, out int value) => GetInt(bytes, ref offset, out value, Endianess.LITTLE); public static byte[] GetInt(this byte[] bytes, ref int offset, out int value, Endianess endianess) { value = GetInt(bytes, ref offset, endianess); return bytes; } public static int GetInt(this byte[] bytes, ref int offset, Endianess endianess) => BitConverter.ToInt32(bytes.Slice(ref offset, 4).To(endianess), 0); public static byte[] GetUInt(this byte[] bytes, ref int offset, out uint value) => GetUInt(bytes, ref offset, out value, Endianess.LITTLE); public static byte[] GetUInt(this byte[] bytes, ref int offset, out uint value, Endianess endianess) { value = GetUInt(bytes, ref offset, endianess); return bytes; } public static uint GetUInt(this byte[] bytes, ref int offset, Endianess endianess) => BitConverter.ToUInt32(bytes.Slice(ref offset, 4).To(endianess), 0); public static byte[] GetBytes(this byte[] bytes,ref int offset,int length,out byte[] value) { value = bytes.Slice(ref offset, length); return bytes; } } }