System.BitConverter.ToUInt16(byte[], int)

Here are the examples of the csharp api System.BitConverter.ToUInt16(byte[], int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1103 Examples 7

19 Source : NetworkUtils.cs
with MIT License
from 1ZouLTReX1

public static ushort DeserializeUshort(byte[] data, ref int offset)
    {
        ushort ret = BitConverter.ToUInt16(data, offset);
        offset += sizeof(ushort);
        return ret;
    }

19 Source : EndianBinaryReader.cs
with MIT License
from 91Act

public override ushort ReadUInt16()
        {
            if (endian == EndianType.BigEndian)
            {
                a16 = ReadBytes(2);
                Array.Reverse(a16);
                return BitConverter.ToUInt16(a16, 0);
            }
            return base.ReadUInt16();
        }

19 Source : WavUtility.cs
with GNU General Public License v3.0
from a2659802

public static AudioClip ToAudioClip(byte[] fileBytes, int offsetSamples = 0, string name = "wav")
		{
			//string riff = Encoding.ASCII.GetString (fileBytes, 0, 4);
			//string wave = Encoding.ASCII.GetString (fileBytes, 8, 4);
			int subchunk1 = BitConverter.ToInt32(fileBytes, 16);
			UInt16 audioFormat = BitConverter.ToUInt16(fileBytes, 20);

			// NB: Only uncompressed PCM wav files are supported.
			string formatCode = FormatCode(audioFormat);
			Debug.replacedertFormat(audioFormat == 1 || audioFormat == 65534, "Detected format code '{0}' {1}, but only PCM and WaveFormatExtensable uncompressed formats are currently supported.", audioFormat, formatCode);

			UInt16 channels = BitConverter.ToUInt16(fileBytes, 22);
			int sampleRate = BitConverter.ToInt32(fileBytes, 24);
			//int byteRate = BitConverter.ToInt32 (fileBytes, 28);
			//UInt16 blockAlign = BitConverter.ToUInt16 (fileBytes, 32);
			UInt16 bitDepth = BitConverter.ToUInt16(fileBytes, 34);

			int headerOffset = 16 + 4 + subchunk1 + 4;
			int subchunk2 = BitConverter.ToInt32(fileBytes, headerOffset);
			//Debug.LogFormat ("riff={0} wave={1} subchunk1={2} format={3} channels={4} sampleRate={5} byteRate={6} blockAlign={7} bitDepth={8} headerOffset={9} subchunk2={10} filesize={11}", riff, wave, subchunk1, formatCode, channels, sampleRate, byteRate, blockAlign, bitDepth, headerOffset, subchunk2, fileBytes.Length);

			float[] data;
			switch (bitDepth)
			{
				case 8:
					data = Convert8BitByteArrayToAudioClipData(fileBytes, headerOffset, subchunk2);
					break;
				case 16:
					data = Convert16BitByteArrayToAudioClipData(fileBytes, headerOffset, subchunk2);
					break;
				case 24:
					data = Convert24BitByteArrayToAudioClipData(fileBytes, headerOffset, subchunk2);
					break;
				case 32:
					data = Convert32BitByteArrayToAudioClipData(fileBytes, headerOffset, subchunk2);
					break;
				default:
					throw new Exception(bitDepth + " bit depth is not supported.");
			}

			AudioClip audioClip = AudioClip.Create(name, data.Length, (int)channels, sampleRate, false);
			audioClip.SetData(data, 0);
			return audioClip;
		}

19 Source : NetworkBitConverter.cs
with MIT License
from a1q123456

public static ushort ToUInt16(Span<byte> buffer, bool littleEndian = false)
        {
            if (!littleEndian)
            {
                buffer.Slice(0, sizeof(ushort)).Reverse();
            }
            return BitConverter.ToUInt16(buffer);
        }

19 Source : GltfConversions.cs
with Apache License 2.0
from abist-co-ltd

private static int GetDiscreteElement(byte[] data, int offset, GltfComponentType type)
        {
            switch (type)
            {
                case GltfComponentType.Byte:
                    return Convert.ToSByte(data[offset]);
                case GltfComponentType.UnsignedByte:
                    return data[offset];
                case GltfComponentType.Short:
                    return BitConverter.ToInt16(data, offset);
                case GltfComponentType.UnsignedShort:
                    return BitConverter.ToUInt16(data, offset);
                case GltfComponentType.UnsignedInt:
                    return (int)BitConverter.ToUInt32(data, offset);
                default:
                    throw new Exception($"Unsupported type preplaceded in: {type}");
            }
        }

19 Source : GltfConversions.cs
with Apache License 2.0
from abist-co-ltd

private static uint GetDiscreteUnsignedElement(byte[] data, int offset, GltfComponentType type)
        {
            switch (type)
            {
                case GltfComponentType.Byte:
                    return (uint)Convert.ToSByte(data[offset]);
                case GltfComponentType.UnsignedByte:
                    return data[offset];
                case GltfComponentType.Short:
                    return (uint)BitConverter.ToInt16(data, offset);
                case GltfComponentType.UnsignedShort:
                    return BitConverter.ToUInt16(data, offset);
                case GltfComponentType.UnsignedInt:
                    return BitConverter.ToUInt32(data, offset);
                default:
                    throw new Exception($"Unsupported type preplaceded in: {type}");
            }
        }

19 Source : Deserializer.cs
with MIT License
from ADeltaX

public static ushort GetUInt16(byte[] data, int index = 0) 
            => BitConverter.ToUInt16(data, index);

19 Source : Extensions.cs
with MIT License
from adrenak

public static ushort ToUShort(this byte[] bytes) {
            return BitConverter.ToUInt16(bytes, 0);
        }

19 Source : ManualMap.cs
with Apache License 2.0
from aequabit

private static uint FindEntryPoint(IntPtr hProcess, IntPtr hModule)
        {
            if (hProcess.IsNull() || hProcess.Compare(-1L))
            {
                throw new ArgumentException("Invalid process handle.", "hProcess");
            }
            if (hModule.IsNull())
            {
                throw new ArgumentException("Invalid module handle.", "hModule");
            }
            byte[] buffer = WinAPI.ReadRemoteMemory(hProcess, hModule, (uint) Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
            if (buffer != null)
            {
                ushort num = BitConverter.ToUInt16(buffer, 0);
                uint num2 = BitConverter.ToUInt32(buffer, 60);
                if (num == 0x5a4d)
                {
                    byte[] buffer2 = WinAPI.ReadRemoteMemory(hProcess, hModule.Add((long) num2), (uint) Marshal.SizeOf(typeof(IMAGE_NT_HEADER32)));
                    if ((buffer2 != null) && (BitConverter.ToUInt32(buffer2, 0) == 0x4550))
                    {
                        IMAGE_NT_HEADER32 result = new IMAGE_NT_HEADER32();
                        using (UnmanagedBuffer buffer3 = new UnmanagedBuffer(0x100))
                        {
                            if (buffer3.Translate<IMAGE_NT_HEADER32>(buffer2, out result))
                            {
                                return result.OptionalHeader.AddressOfEntryPoint;
                            }
                        }
                    }
                }
            }
            return 0;
        }

19 Source : WinAPI.cs
with Apache License 2.0
from aequabit

public static IntPtr GetProcAddressEx(IntPtr hProc, IntPtr hModule, object lpProcName)
        {
            IntPtr zero = IntPtr.Zero;
            byte[] buffer = ReadRemoteMemory(hProc, hModule, 0x40);
            if ((buffer == null) || (BitConverter.ToUInt16(buffer, 0) != 0x5a4d))
            {
                return zero;
            }
            uint num = BitConverter.ToUInt32(buffer, 60);
            if (num <= 0)
            {
                return zero;
            }
            byte[] buffer2 = ReadRemoteMemory(hProc, hModule.Add((long) num), 0x108);
            if ((buffer2 == null) || (BitConverter.ToUInt32(buffer2, 0) != 0x4550))
            {
                return zero;
            }
            uint num2 = BitConverter.ToUInt32(buffer2, 120);
            uint num3 = BitConverter.ToUInt32(buffer2, 0x7c);
            if ((num2 <= 0) || (num3 <= 0))
            {
                return zero;
            }
            byte[] buffer3 = ReadRemoteMemory(hProc, hModule.Add((long) num2), 40);
            uint num4 = BitConverter.ToUInt32(buffer3, 0x1c);
            uint num5 = BitConverter.ToUInt32(buffer3, 0x24);
            uint num6 = BitConverter.ToUInt32(buffer3, 20);
            int num7 = -1;
            if ((num4 <= 0) || (num5 <= 0))
            {
                return zero;
            }
            if (lpProcName.GetType().Equals(typeof(string)))
            {
                int num8 = SearchExports(hProc, hModule, buffer3, (string) lpProcName);
                if (num8 > -1)
                {
                    byte[] buffer4 = ReadRemoteMemory(hProc, hModule.Add((long) (num5 + (num8 << 1))), 2);
                    num7 = (buffer4 == null) ? -1 : BitConverter.ToUInt16(buffer4, 0);
                }
            }
            else if (lpProcName.GetType().Equals(typeof(short)) || lpProcName.GetType().Equals(typeof(ushort)))
            {
                num7 = int.Parse(lpProcName.ToString());
            }
            if ((num7 <= -1) || (num7 >= num6))
            {
                return zero;
            }
            byte[] buffer5 = ReadRemoteMemory(hProc, hModule.Add((long) (num4 + (num7 << 2))), 4);
            if (buffer5 == null)
            {
                return zero;
            }
            uint num9 = BitConverter.ToUInt32(buffer5, 0);
            if ((num9 >= num2) && (num9 < (num2 + num3)))
            {
                string str = ReadRemoteString(hProc, hModule.Add((long) num9), null);
                if (!(string.IsNullOrEmpty(str) || !str.Contains(".")))
                {
                    zero = GetProcAddressEx(hProc, GetModuleHandleEx(hProc, str.Split(new char[] { '.' })[0]), str.Split(new char[] { '.' })[1]);
                }
                return zero;
            }
            return hModule.Add(((long) num9));
        }

19 Source : utils.cs
with GNU General Public License v3.0
from Aeroblast

public static UInt16 GetUInt16(byte[] src, ulong start)
        {
            byte[] t = SubArray(src, start, 2);
            Array.Reverse(t);
            return BitConverter.ToUInt16(t);
        }

19 Source : Volume.cs
with MIT License
from aerosoul94

private void ReadFileAllocationTable()
        {
            _fileAllocationTable = new uint[_maxClusters];

            var fatOffset = ByteOffsetToPhysicalOffset(this._fatByteOffset);
            _reader.Seek(fatOffset);
            if (this._isFat16)
            {
                byte[] _tempFat = new byte[_maxClusters * 2];
                _reader.Read(_tempFat, (int)(_maxClusters * 2));

                if (_reader.ByteOrder == ByteOrder.Big)
                {
                    for (int i = 0; i < _maxClusters; i++)
                    {
                        Array.Reverse(_tempFat, i * 2, 2);
                    }
                }

                for (int i = 0; i < _maxClusters; i++)
                {
                    _fileAllocationTable[i] = BitConverter.ToUInt16(_tempFat, i * 2);
                }
            }
            else
            {
                byte[] _tempFat = new byte[_maxClusters * 4];
                _reader.Read(_tempFat, (int)(_maxClusters * 4));

                if (_reader.ByteOrder == ByteOrder.Big)
                {
                    for (int i = 0; i < _maxClusters; i++)
                    {
                        Array.Reverse(_tempFat, i * 4, 4);
                    }
                }

                for (int i = 0; i < _maxClusters; i++)
                {
                    _fileAllocationTable[i] = BitConverter.ToUInt32(_tempFat, i * 4);
                }
            }
        }

19 Source : EndianReader.cs
with MIT License
from aerosoul94

public override ushort ReadUInt16()
        {
            var temp = new byte[2];
            Read(temp, 2);
            if (byteOrder == ByteOrder.Big)
            {
                Array.Reverse(temp);
            }
            return BitConverter.ToUInt16(temp, 0);
        }

19 Source : ZFrame.cs
with Mozilla Public License 2.0
from agebullhu

public UInt16 ReadUInt16()
        {
            var bytes = new byte[2];
            if (Read(bytes, 0, 2) < 2)
            {
                return default(UInt16);
            }

            return BitConverter.ToUInt16(bytes, 0);
        }

19 Source : Mesh.cs
with GNU General Public License v3.0
from ahmed605

public ushort[] DecodeIndexData()
        {
            byte[] indexData = IndexData;
            ushort[] indices = new ushort[IndexCount];
            for (int i = 0; i < IndexCount; i++)
            {
                indices[i] = BitConverter.ToUInt16(indexData, i*2);
            }
            return indices;
        }

19 Source : DXTDecoder.cs
with GNU General Public License v3.0
from ahmed605

internal static byte[] DecodeDXT1(byte[] data, int width, int height)
        {
            byte[] pixData = new byte[width * height * 4];
            int xBlocks = width / 4;
            int yBlocks = height / 4;
            for (int y = 0; y < yBlocks; y++)
            {
                for (int x = 0; x < xBlocks; x++)
                {
                    int blockDataStart = ((y * xBlocks) + x) * 8;

#if XBOX360
                    uint color0 = ((uint)data[blockDataStart + 0] << 8) + data[blockDataStart + 1];
                    uint color1 = ((uint)data[blockDataStart + 2] << 8) + data[blockDataStart + 3];
#else
                    uint color0 = BitConverter.ToUInt16(data, blockDataStart);
                    uint color1 = BitConverter.ToUInt16(data, blockDataStart + 2);
#endif

                    uint code = BitConverter.ToUInt32(data, blockDataStart + 4);

                    ushort r0 = 0, g0 = 0, b0 = 0, r1 = 0, g1 = 0, b1 = 0;
                    r0 = (ushort)(8 * (color0 & 31));
                    g0 = (ushort)(4 * ((color0 >> 5) & 63));
                    b0 = (ushort)(8 * ((color0 >> 11) & 31));

                    r1 = (ushort)(8 * (color1 & 31));
                    g1 = (ushort)(4 * ((color1 >> 5) & 63));
                    b1 = (ushort)(8 * ((color1 >> 11) & 31));

                    for (int k = 0; k < 4; k++)
                    {
#if XBOX360
                        int j = k ^ 1;
#else
                        int j = k;
#endif

                        for (int i = 0; i < 4; i++)
                        {
                            int pixDataStart = (width * (y * 4 + j) * 4) + ((x * 4 + i) * 4);
                            uint codeDec = code & 0x3;

                            switch (codeDec)
                            {
                                case 0:
                                    pixData[pixDataStart + 0] = (byte)r0;
                                    pixData[pixDataStart + 1] = (byte)g0;
                                    pixData[pixDataStart + 2] = (byte)b0;
                                    pixData[pixDataStart + 3] = 255;
                                    break;
                                case 1:
                                    pixData[pixDataStart + 0] = (byte)r1;
                                    pixData[pixDataStart + 1] = (byte)g1;
                                    pixData[pixDataStart + 2] = (byte)b1;
                                    pixData[pixDataStart + 3] = 255;
                                    break;
                                case 2:
                                    pixData[pixDataStart + 3] = 255;
                                    if (color0 > color1)
                                    {
                                        pixData[pixDataStart + 0] = (byte)((2 * r0 + r1) / 3);
                                        pixData[pixDataStart + 1] = (byte)((2 * g0 + g1) / 3);
                                        pixData[pixDataStart + 2] = (byte)((2 * b0 + b1) / 3);
                                    }
                                    else
                                    {
                                        pixData[pixDataStart + 0] = (byte)((r0 + r1) / 2);
                                        pixData[pixDataStart + 1] = (byte)((g0 + g1) / 2);
                                        pixData[pixDataStart + 2] = (byte)((b0 + b1) / 2);
                                    }
                                    break;
                                case 3:
                                    if (color0 > color1)
                                    {
                                        pixData[pixDataStart + 0] = (byte)((r0 + 2 * r1) / 3);
                                        pixData[pixDataStart + 1] = (byte)((g0 + 2 * g1) / 3);
                                        pixData[pixDataStart + 2] = (byte)((b0 + 2 * b1) / 3);
                                        pixData[pixDataStart + 3] = 255;
                                    }
                                    else
                                    {
                                        pixData[pixDataStart + 0] = 0;
                                        pixData[pixDataStart + 1] = 0;
                                        pixData[pixDataStart + 2] = 0;
                                        pixData[pixDataStart + 3] = 0;
                                    }
                                    break;
                            }

                            code >>= 2;
                        }
                    }


                }
            }
            return pixData;
        }

19 Source : DXTDecoder.cs
with GNU General Public License v3.0
from ahmed605

internal static byte[] DecodeDXT3(byte[] data, int width, int height)
        {
            byte[] pixData = new byte[width * height * 4];
            int xBlocks = width / 4;
            int yBlocks = height / 4;
            for (int y = 0; y < yBlocks; y++)
            {
                for (int x = 0; x < xBlocks; x++)
                {
                    int blockDataStart = ((y * xBlocks) + x) * 16;
                    ushort[] alphaData = new ushort[4];
                    
#if XBOX360
                    alphaData[0] = (ushort)((data[blockDataStart + 0] << 8) + data[blockDataStart + 1]);
                    alphaData[1] = (ushort)((data[blockDataStart + 2] << 8) + data[blockDataStart + 3]);
                    alphaData[2] = (ushort)((data[blockDataStart + 4] << 8) + data[blockDataStart + 5]);
                    alphaData[3] = (ushort)((data[blockDataStart + 6] << 8) + data[blockDataStart + 7]);
#else
                    alphaData[0] = BitConverter.ToUInt16(data, blockDataStart + 0);
                    alphaData[1] = BitConverter.ToUInt16(data, blockDataStart + 2);
                    alphaData[2] = BitConverter.ToUInt16(data, blockDataStart + 4);
                    alphaData[3] = BitConverter.ToUInt16(data, blockDataStart + 6);
#endif

                    byte[,] alpha = new byte[4, 4];
                    for (int j = 0; j < 4; j++)
                    {
                        for (int i = 0; i < 4; i++)
                        {
                            alpha[i, j] = (byte)((alphaData[j] & 0xF) * 16);
                            alphaData[j] >>= 4;
                        }
                    }

#if XBOX360
                    ushort color0 = (ushort)((data[blockDataStart + 8] << 8) + data[blockDataStart + 9]);
                    ushort color1 = (ushort)((data[blockDataStart + 10] << 8) + data[blockDataStart + 11]);
#else
                    ushort color0 = BitConverter.ToUInt16(data, blockDataStart + 8);
                    ushort color1 = BitConverter.ToUInt16(data, blockDataStart + 8 + 2);
#endif

                    uint code = BitConverter.ToUInt32(data, blockDataStart + 8 + 4);

                    ushort r0 = 0, g0 = 0, b0 = 0, r1 = 0, g1 = 0, b1 = 0;
                    r0 = (ushort)(8 * (color0 & 31));
                    g0 = (ushort)(4 * ((color0 >> 5) & 63));
                    b0 = (ushort)(8 * ((color0 >> 11) & 31));

                    r1 = (ushort)(8 * (color1 & 31));
                    g1 = (ushort)(4 * ((color1 >> 5) & 63));
                    b1 = (ushort)(8 * ((color1 >> 11) & 31));

                    for (int k = 0; k < 4; k++)
                    {
#if XBOX360
                        int j = k ^ 1;
#else
                        int j = k;
#endif
                        
                        for (int i = 0; i < 4; i++)
                        {
                            int pixDataStart = (width * (y * 4 + j) * 4) + ((x * 4 + i) * 4);
                            uint codeDec = code & 0x3;

                            pixData[pixDataStart + 3] = alpha[i, j];

                            switch (codeDec)
                            {
                                case 0:
                                    pixData[pixDataStart + 0] = (byte)r0;
                                    pixData[pixDataStart + 1] = (byte)g0;
                                    pixData[pixDataStart + 2] = (byte)b0;
                                    break;
                                case 1:
                                    pixData[pixDataStart + 0] = (byte)r1;
                                    pixData[pixDataStart + 1] = (byte)g1;
                                    pixData[pixDataStart + 2] = (byte)b1;
                                    break;
                                case 2:
                                    if (color0 > color1)
                                    {
                                        pixData[pixDataStart + 0] = (byte)((2 * r0 + r1) / 3);
                                        pixData[pixDataStart + 1] = (byte)((2 * g0 + g1) / 3);
                                        pixData[pixDataStart + 2] = (byte)((2 * b0 + b1) / 3);
                                    }
                                    else
                                    {
                                        pixData[pixDataStart + 0] = (byte)((r0 + r1) / 2);
                                        pixData[pixDataStart + 1] = (byte)((g0 + g1) / 2);
                                        pixData[pixDataStart + 2] = (byte)((b0 + b1) / 2);
                                    }
                                    break;
                                case 3:
                                    if (color0 > color1)
                                    {
                                        pixData[pixDataStart + 0] = (byte)((r0 + 2 * r1) / 3);
                                        pixData[pixDataStart + 1] = (byte)((g0 + 2 * g1) / 3);
                                        pixData[pixDataStart + 2] = (byte)((b0 + 2 * b1) / 3);
                                    }
                                    else
                                    {
                                        pixData[pixDataStart + 0] = 0;
                                        pixData[pixDataStart + 1] = 0;
                                        pixData[pixDataStart + 2] = 0;
                                    }
                                    break;
                            }

                            code >>= 2;
                        }
                    }


                }
            }
            return pixData;
        }

19 Source : DXTDecoder.cs
with GNU General Public License v3.0
from ahmed605

internal static byte[] DecodeDXT5(byte[] data, int width, int height)
        {
            byte[] pixData = new byte[width * height * 4];
            int xBlocks = width / 4;
            int yBlocks = height / 4;
            for (int y = 0; y < yBlocks; y++)
            {
                for (int x = 0; x < xBlocks; x++)
                {
                    int blockDataStart = ((y * xBlocks) + x) * 16;
                    uint[] alphas = new uint[8];
                    ulong alphaMask = 0;

#if XBOX360

                    alphas[0] = data[blockDataStart + 1];
                    alphas[1] = data[blockDataStart + 0];

                    alphaMask |= data[blockDataStart + 6];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 7];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 4];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 5];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 2];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 3];

#else

                    alphas[0] = data[blockDataStart + 0];
                    alphas[1] = data[blockDataStart + 1];

                    alphaMask |= data[blockDataStart + 7];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 6];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 5];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 4];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 3];
                    alphaMask <<= 8;
                    alphaMask |= data[blockDataStart + 2];

#endif

                    // 8-alpha or 6-alpha block
                    if (alphas[0] > alphas[1])
                    {
                        // 8-alpha block: derive the other 6
                        // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
                        alphas[2] = (byte)((6 * alphas[0] + 1 * alphas[1] + 3) / 7);    // bit code 010
                        alphas[3] = (byte)((5 * alphas[0] + 2 * alphas[1] + 3) / 7);    // bit code 011
                        alphas[4] = (byte)((4 * alphas[0] + 3 * alphas[1] + 3) / 7);    // bit code 100
                        alphas[5] = (byte)((3 * alphas[0] + 4 * alphas[1] + 3) / 7);    // bit code 101
                        alphas[6] = (byte)((2 * alphas[0] + 5 * alphas[1] + 3) / 7);    // bit code 110
                        alphas[7] = (byte)((1 * alphas[0] + 6 * alphas[1] + 3) / 7);    // bit code 111
                    }
                    else
                    {
                        // 6-alpha block.
                        // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
                        alphas[2] = (byte)((4 * alphas[0] + 1 * alphas[1] + 2) / 5);    // Bit code 010
                        alphas[3] = (byte)((3 * alphas[0] + 2 * alphas[1] + 2) / 5);    // Bit code 011
                        alphas[4] = (byte)((2 * alphas[0] + 3 * alphas[1] + 2) / 5);    // Bit code 100
                        alphas[5] = (byte)((1 * alphas[0] + 4 * alphas[1] + 2) / 5);    // Bit code 101
                        alphas[6] = 0x00;                                               // Bit code 110
                        alphas[7] = 0xFF;                                               // Bit code 111
                    }

                    byte[,] alpha = new byte[4, 4];

                    for (int i = 0; i < 4; i++)
                    {
                        for (int j = 0; j < 4; j++)
                        {
                            alpha[j, i] = (byte)alphas[alphaMask & 7];
                            alphaMask >>= 3;
                        }
                    }

#if XBOX360
                    ushort color0 = (ushort)((data[blockDataStart + 8] << 8) + data[blockDataStart + 9]);
                    ushort color1 = (ushort)((data[blockDataStart + 10] << 8) + data[blockDataStart + 11]);
#else
                    ushort color0 = BitConverter.ToUInt16(data, blockDataStart + 8);
                    ushort color1 = BitConverter.ToUInt16(data, blockDataStart + 8 + 2);
#endif

                    uint code = BitConverter.ToUInt32(data, blockDataStart + 8 + 4);

                    ushort r0 = 0, g0 = 0, b0 = 0, r1 = 0, g1 = 0, b1 = 0;
                    r0 = (ushort)(8 * (color0 & 31));
                    g0 = (ushort)(4 * ((color0 >> 5) & 63));
                    b0 = (ushort)(8 * ((color0 >> 11) & 31));

                    r1 = (ushort)(8 * (color1 & 31));
                    g1 = (ushort)(4 * ((color1 >> 5) & 63));
                    b1 = (ushort)(8 * ((color1 >> 11) & 31));

                    for (int k = 0; k < 4; k++)
                    {
#if XBOX360
                        int j = k ^ 1;
#else
                        int j = k;
#endif

                        for (int i = 0; i < 4; i++)
                        {
                            int pixDataStart = (width * (y * 4 + j) * 4) + ((x * 4 + i) * 4);
                            uint codeDec = code & 0x3;

                            pixData[pixDataStart + 3] = alpha[i, j];

                            switch (codeDec)
                            {
                                case 0:
                                    pixData[pixDataStart + 0] = (byte)r0;
                                    pixData[pixDataStart + 1] = (byte)g0;
                                    pixData[pixDataStart + 2] = (byte)b0;
                                    break;
                                case 1:
                                    pixData[pixDataStart + 0] = (byte)r1;
                                    pixData[pixDataStart + 1] = (byte)g1;
                                    pixData[pixDataStart + 2] = (byte)b1;
                                    break;
                                case 2:
                                    if (color0 > color1)
                                    {
                                        pixData[pixDataStart + 0] = (byte)((2 * r0 + r1) / 3);
                                        pixData[pixDataStart + 1] = (byte)((2 * g0 + g1) / 3);
                                        pixData[pixDataStart + 2] = (byte)((2 * b0 + b1) / 3);
                                    }
                                    else
                                    {
                                        pixData[pixDataStart + 0] = (byte)((r0 + r1) / 2);
                                        pixData[pixDataStart + 1] = (byte)((g0 + g1) / 2);
                                        pixData[pixDataStart + 2] = (byte)((b0 + b1) / 2);
                                    }
                                    break;
                                case 3:
                                    if (color0 > color1)
                                    {
                                        pixData[pixDataStart + 0] = (byte)((r0 + 2 * r1) / 3);
                                        pixData[pixDataStart + 1] = (byte)((g0 + 2 * g1) / 3);
                                        pixData[pixDataStart + 2] = (byte)((b0 + 2 * b1) / 3);
                                    }
                                    else
                                    {
                                        pixData[pixDataStart + 0] = 0;
                                        pixData[pixDataStart + 1] = 0;
                                        pixData[pixDataStart + 2] = 0;
                                    }
                                    break;
                            }

                            code >>= 2;
                        }
                    }


                }
            }
            return pixData;
        }

19 Source : AccessPolicy.cs
with GNU General Public License v3.0
from aiportal

private string GetConnectedUser(int processPort, AddressFamily addressFamily)
		{
			int pid = 0;
			int dwProcessPort = BitConverter.ToUInt16(new byte[] { BitConverter.GetBytes(processPort)[1], BitConverter.GetBytes(processPort)[0] }, 0);
			if (addressFamily == AddressFamily.InterNetwork)
			{
				foreach (var conn in EnumTcpConnectionsV4())
				{
					if (conn.dwLocalPort == dwProcessPort)
					{
						pid = conn.dwOwningPid;
						break;
					}
				}
			}
			else if (addressFamily == AddressFamily.InterNetworkV6)
			{
				foreach (var conn in EnumTcpConnectionsV6())
				{
					if (conn.dwLocalPort == dwProcessPort)
					{
						pid = conn.dwOwningPid;
						break;
					}
				}
			}
			if (pid > 0)
			{
				using (Process proc = Process.GetProcessById(pid))
				{
					if (proc != null)
					{
						string user = GetDomainUserBySessionId(proc.SessionId);
						proc.Dispose();
						return DomainUser.Create(user).ToString();
					}
				}
			}
			return null;
		}

19 Source : TcpEngine.cs
with GNU General Public License v3.0
from aiportal

public static int GetConnectedProcess(IPEndPoint remoteEndPoint)
		{
			Debug.replacedert(IPAddress.IsLoopback(remoteEndPoint.Address));
			{
				byte[] bsPort = BitConverter.GetBytes(remoteEndPoint.Port);
				int dwPort = BitConverter.ToUInt16(new byte[] { bsPort[1], bsPort[0] }, 0);
				if (remoteEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
				{
					foreach (var conn in EnumTcpConnectionsV4())
					{
						if (conn.dwLocalPort == dwPort)
							return conn.dwOwningPid;
					}
				}
				if (remoteEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
				{
					foreach (var conn in EnumTcpConnectionsV6())
					{
						if (conn.dwLocalPort == dwPort)
							return conn.dwOwningPid;
					}
				}
				return 0;
			}
		}

19 Source : Utils.cs
with Apache License 2.0
from ajuna-network

public static object Bytes2Value(byte[] value, bool littleEndian = true)
        {
            if (!littleEndian) Array.Reverse(value);

            switch (value.Length)
            {
                case 2:
                    return BitConverter.ToUInt16(value, 0);
                case 4:
                    return BitConverter.ToUInt32(value, 0);
                case 8:
                    return BitConverter.ToUInt64(value, 0);
                default:
                    throw new Exception($"Unhandled byte size {value.Length} for this method!");
            }
        }

19 Source : U16.cs
with Apache License 2.0
from ajuna-network

public override void Create(byte[] byteArray)
        {
            if (byteArray.Length < Size())
            {
                var newByteArray = new byte[Size()];
                byteArray.CopyTo(newByteArray, 0);
                byteArray = newByteArray;
            }

            Bytes = byteArray;
            Value = BitConverter.ToUInt16(byteArray, 0);
        }

19 Source : UnnyNetPacker.cs
with MIT License
from alerdenisov

static public object[] UnpackObject(byte[] bytes, int bytesCount)
    {
        object[] arg = new object[1];
        arg[0] = 0;
        int size = 0;
        int num = HeaderSize;
        try
        {
            while (num < bytesCount)
            {
                switch ((TypeTags)bytes[num++])
                {
                    case TypeTags.IntTag:
                        {
                            if (num + 4 <= bytesCount)
                            {
                                int intValue = System.BitConverter.ToInt32(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 4;
                            break;
                        }
                    case TypeTags.FloatTag:
                        {
                            if (num + 4 <= bytesCount)
                            {
                                var floatValue = System.BitConverter.ToSingle(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = floatValue;
                            }
                            num += 4;
                            break;
                        }
                    case TypeTags.Vector3Tag:
                        {
                            if (num + 12 <= bytesCount)
                            {
                                var vecValue = new Vector3();
                                for (int axis = 0; axis < 3; axis++)
                                {
                                    vecValue[axis] = System.BitConverter.ToSingle(bytes, num + (4 * axis));
                                }

                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = vecValue;
                            }
                            num += 12;
                            break;
                        }
                    case TypeTags.UIntTag:
                        {
                            if (num + 4 <= bytesCount)
                            {
                                uint intValue = System.BitConverter.ToUInt32(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 4;
                            break;
                        }
                    case TypeTags.LongTag:
                        {
                            if (num + 8 <= bytesCount)
                            {
                                long intValue = System.BitConverter.ToInt64(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 8;
                            break;
                        }
                    case TypeTags.ULongTag:
                        {
                            if (num + 8 <= bytesCount)
                            {
                                ulong intValue = System.BitConverter.ToUInt64(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 8;
                            break;
                        }
                    case TypeTags.ShortTag:
                        {
                            if (num + 2 <= bytesCount)
                            {
                                short intValue = System.BitConverter.ToInt16(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 2;
                            break;
                        }
                    case TypeTags.UShortTag:
                        {
                            if (num + 2 <= bytesCount)
                            {
                                ushort intValue = System.BitConverter.ToUInt16(bytes, num);
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = intValue;
                            }
                            num += 2;
                            break;
                        }
                    case TypeTags.ByteTag:
                        {
                            System.Array.Resize(ref arg, size + 1);
                            arg[size++] = bytes[num++];
                            break;
                        }
                    case TypeTags.SByteTag:
                        {
                            System.Array.Resize(ref arg, size + 1);
                            arg[size++] = (sbyte)bytes[num++];
                            break;
                        }
                    case TypeTags.BoolTag:
                        {
                            System.Array.Resize(ref arg, size + 1);
                            arg[size++] = (bytes[num++] == 1);
                            break;
                        }
                    case TypeTags.StringTag:
                        {
                            if (num + 2 <= bytesCount)
                            {
                                ushort intValue = System.BitConverter.ToUInt16(bytes, num);
                                num += 2;
                                if (num + intValue <= bytesCount)
                                {
                                    System.Array.Resize(ref arg, size + 1);
                                    arg[size++] = System.Text.Encoding.UTF8.GetString(bytes, num, intValue);
                                }
                                num += intValue;
                            }
                            else
                                num += 2;
                            break;
                        }
                    case TypeTags.UShortArraySmall:
                        {
                            byte length = bytes[num++];
                            if (num + 2 * length <= bytesCount)
                            {
                                ushort[] arr = new ushort[length];
                                for (int j = 0; j < length; j++)
                                {
                                    arr[j] = System.BitConverter.ToUInt16(bytes, num);
                                    num += 2;
                                }
                                System.Array.Resize(ref arg, size + 1);
                                arg[size++] = arr;
                            }
                            else
                                num += 2 * length;
                            break;
                        }
                    case TypeTags.UShortArrayBig:
                        {
                            if (num + 2 <= bytesCount)
                            {
                                ushort length = System.BitConverter.ToUInt16(bytes, num);
                                num += 2;

                                if (num + 2 * length <= bytesCount)
                                {
                                    ushort[] arr = new ushort[length];

                                    for (int j = 0; j < length; j++)
                                    {
                                        arr[j] = System.BitConverter.ToUInt16(bytes, num);
                                        num += 2;
                                    }
                                    System.Array.Resize(ref arg, size + 1);
                                    arg[size++] = arr;
                                }
                                else
                                    num += 2 * length;
                            }
                            else
                                num += 2;
                            break;
                        }
                    default:
                        Debug.Log("Couldn't unpack");
                        return arg;
                }
            }
        }
        catch (System.ArgumentException e)
        {
            Debug.Log("e = " + e);
        }
        return arg;
    }

19 Source : WavUtility.cs
with MIT License
from alessandroTironi

public static AudioClip ToAudioClip (byte[] fileBytes, int offsetSamples = 0, string name = "wav")
	{
		//string riff = Encoding.ASCII.GetString (fileBytes, 0, 4);
		//string wave = Encoding.ASCII.GetString (fileBytes, 8, 4);
		int subchunk1 = BitConverter.ToInt32 (fileBytes, 16);
		UInt16 audioFormat = BitConverter.ToUInt16 (fileBytes, 20);

		// NB: Only uncompressed PCM wav files are supported.
		string formatCode = FormatCode (audioFormat);
		Debug.replacedertFormat (audioFormat == 1 || audioFormat == 65534, "Detected format code '{0}' {1}, but only PCM and WaveFormatExtensable uncompressed formats are currently supported.", audioFormat, formatCode);

		UInt16 channels = BitConverter.ToUInt16 (fileBytes, 22);
		int sampleRate = BitConverter.ToInt32 (fileBytes, 24);
		//int byteRate = BitConverter.ToInt32 (fileBytes, 28);
		//UInt16 blockAlign = BitConverter.ToUInt16 (fileBytes, 32);
		UInt16 bitDepth = BitConverter.ToUInt16 (fileBytes, 34);

		int headerOffset = 16 + 4 + subchunk1 + 4;
		int subchunk2 = BitConverter.ToInt32 (fileBytes, headerOffset);
		//Debug.LogFormat ("riff={0} wave={1} subchunk1={2} format={3} channels={4} sampleRate={5} byteRate={6} blockAlign={7} bitDepth={8} headerOffset={9} subchunk2={10} filesize={11}", riff, wave, subchunk1, formatCode, channels, sampleRate, byteRate, blockAlign, bitDepth, headerOffset, subchunk2, fileBytes.Length);

		float[] data;
		switch (bitDepth) {
		case 8:
			data = Convert8BitByteArrayToAudioClipData (fileBytes, headerOffset, subchunk2);
			break;
		case 16:
			data = Convert16BitByteArrayToAudioClipData (fileBytes, headerOffset, subchunk2);
			break;
		case 24:
			data = Convert24BitByteArrayToAudioClipData (fileBytes, headerOffset, subchunk2);
			break;
		case 32:
			data = Convert32BitByteArrayToAudioClipData (fileBytes, headerOffset, subchunk2);
			break;
		default:
			throw new Exception (bitDepth + " bit depth is not supported.");
		}

		AudioClip audioClip = AudioClip.Create (name, data.Length, (int)channels, sampleRate, false);
		audioClip.SetData (data, 0);
		return audioClip;
	}

19 Source : BitStream.cs
with MIT License
from Alexander-Scott

public ushort ReadUInt16()
        {
            ushort value = BitConverter.ToUInt16(ReadBytes(16), 0);
            return value;
        }

19 Source : MemoryUtil.cs
with GNU General Public License v3.0
from am0nsec

protected UInt16 ReadUShort(Int64 offset) {
            Span<byte> s = stackalloc byte[2];
            this.ModuleStream.Seek(offset, SeekOrigin.Begin);
            this.ModuleStream.Read(s);
            return BitConverter.ToUInt16(s);
        }

19 Source : NetworkClass.cs
with GNU General Public License v2.0
from AmanoTooko

private void MessageSent(long epoch, byte[] message, int set, FFXIVNetworkMonitor.ConnectionType connectionType)
        {
            try
            {
                var res = Parse(message);
                if (res.header.MessageType == ParameterController.instruSendingPacket) //Bard Performance 
                {
                   var type = BitConverter.ToUInt16(res.data, 32);
                    if (type == (0x071C))
                    {
                        byte data = res.data[36];
                        if (data <= 19)
                        {
                            Play?.Invoke(this, new PlayEvent(2, 0, constStringClreplaced.IDtoString(data)));
                            Log.overlayLog($"乐器更换:{constStringClreplaced.IDtoString(data)}");
                        }

                    }

                }
            }
            catch (Exception e)
            {
                Log.overlayLog(e.ToString());
                
            }

        }

19 Source : ModbusServer.cs
with MIT License
from AndreasAmMueller

private async Task HandleClient(TcpClient client)
		{
			logger?.LogTrace("ModbusServer.HandleClient enter");
			var endpoint = (IPEndPoint)client.Client.RemoteEndPoint;
			try
			{
				ClientConnected?.Invoke(this, new ClientEventArgs(endpoint));
				logger?.LogInformation($"Client connected: {endpoint.Address}.");

				var stream = client.GetStream();
				while (!stopCts.IsCancellationRequested)
				{
					using var requestStream = new MemoryStream();

					using (var cts = new CancellationTokenSource(Timeout))
					using (stopCts.Token.Register(() => cts.Cancel()))
					{
						try
						{
							byte[] header = await stream.ReadExpectedBytes(6, cts.Token);
							await requestStream.WriteAsync(header, 0, header.Length, cts.Token);

							byte[] bytes = header.Skip(4).Take(2).ToArray();
							if (BitConverter.IsLittleEndian)
								Array.Reverse(bytes);

							int following = BitConverter.ToUInt16(bytes, 0);
							byte[] payload = await stream.ReadExpectedBytes(following, cts.Token);
							await requestStream.WriteAsync(payload, 0, payload.Length, cts.Token);
						}
						catch (OperationCanceledException) when (cts.IsCancellationRequested)
						{
							continue;
						}
					}

					try
					{
						var request = new Request(requestStream.GetBuffer());
						var response = requestHandler?.Invoke(request, stopCts.Token);
						if (response != null)
						{
							using var cts = new CancellationTokenSource(Timeout);
							using var reg = stopCts.Token.Register(() => cts.Cancel());
							try
							{
								byte[] bytes = response.Serialize();
								await stream.WriteAsync(bytes, 0, bytes.Length, cts.Token);
							}
							catch (OperationCanceledException) when (cts.IsCancellationRequested)
							{
								continue;
							}
						}
					}
					catch (ArgumentException ex)
					{
						logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
					}
					catch (NotImplementedException ex)
					{
						logger?.LogWarning(ex, $"Invalid data received from {endpoint.Address}: {ex.Message}");
					}
				}
			}
			catch (IOException)
			{
				// client connection closed
				return;
			}
			catch (Exception ex)
			{
				logger?.LogError(ex, $"Unexpected error ({ex.GetType().Name}) occurred: {ex.GetMessage()}");
			}
			finally
			{
				ClientDisconnected?.Invoke(this, new ClientEventArgs(endpoint));
				logger?.LogInformation($"Client disconnected: {endpoint.Address}");

				client.Dispose();
				tcpClients.TryRemove(client, out _);

				logger?.LogTrace("ModbusServer.HandleClient leave");
			}
		}

19 Source : ModbusClient.cs
with MIT License
from AndreasAmMueller

private async Task ReceiveLoop()
		{
			try
			{
				logger?.LogTrace("ModbusClient.ReceiveLoop enter");
				logger?.LogInformation("Receiving responses started.");

				while (!receiveCts.IsCancellationRequested)
				{
					try
					{
						if (stream == null)
						{
							await Task.Delay(200, receiveCts.Token);
							continue;
						}

						while (!receiveCts.IsCancellationRequested)
						{
							using var responseStream = new MemoryStream();

							using (var timeCts = new CancellationTokenSource(ReceiveTimeout))
							using (var cts = CancellationTokenSource.CreateLinkedTokenSource(timeCts.Token, receiveCts.Token))
							{
								try
								{
									byte[] header = await stream.ReadExpectedBytes(6, cts.Token);
									await responseStream.WriteAsync(header, 0, header.Length, cts.Token);

									byte[] bytes = header.Skip(4).Take(2).ToArray();
									if (BitConverter.IsLittleEndian)
										Array.Reverse(bytes);

									int following = BitConverter.ToUInt16(bytes, 0);
									byte[] payload = await stream.ReadExpectedBytes(following, cts.Token);
									await responseStream.WriteAsync(payload, 0, payload.Length, cts.Token);
								}
								catch (OperationCanceledException) when (timeCts.IsCancellationRequested)
								{
									continue;
								}
							}

							try
							{
								var response = new Response(responseStream.GetBuffer());

								QueuedRequest queueItem = null;
								await queueLock.WaitAsync(receiveCts.Token);
								try
								{
									if (DisableTransactionId)
									{
										queueItem = awaitingResponses.FirstOrDefault();
									}
									else
									{
										queueItem = awaitingResponses
											.Where(i => i.TransactionId == response.TransactionId)
											.FirstOrDefault();
										if (queueItem == null)
											logger?.LogWarning($"Received response for transaction #{response.TransactionId}. The matching request could not be resolved.");
									}

									if (queueItem != null)
									{
										queueItem.Registration.Dispose();
										awaitingResponses.Remove(queueItem);
									}
								}
								finally
								{
									queueLock.Release();
								}

								if (queueItem != null)
								{
									if (!DisableTransactionId)
										logger?.LogDebug($"Received response for transaction #{response.TransactionId}.");

									queueItem.CancellationTokenSource.Dispose();
									queueItem.TaskCompletionSource.TrySetResult(response);
									queueItem.TimeoutCancellationTokenSource.Dispose();
								}
							}
							catch (ArgumentException ex)
							{
								logger?.LogError(ex, $"Invalid data received: {ex.Message}");
							}
							catch (NotImplementedException ex)
							{
								logger?.LogError(ex, $"Invalid data received: {ex.Message}");
							}
						}
					}
					catch (OperationCanceledException) when (receiveCts.IsCancellationRequested)
					{
						// Receive loop stopping
						throw;
					}
					catch (IOException)
					{
						if (!isReconnecting)
							ConnectingTask = GetReconnectTask();

						await Task.Delay(1, receiveCts.Token);   // make sure the reconnect task has time to start.
					}
					catch (Exception ex)
					{
						logger?.LogError(ex, $"Unexpected error ({ex.GetType().Name}) on receive: {ex.GetMessage()}");
					}
				}
			}
			catch (OperationCanceledException) when (receiveCts.IsCancellationRequested)
			{
				// Receive loop stopping
				var ex = new SocketException((int)SocketError.TimedOut);

				await queueLock.WaitAsync(stopCts.Token);
				try
				{
					foreach (var queuedItem in awaitingResponses)
					{
						queuedItem.Registration.Dispose();
						queuedItem.CancellationTokenSource.Dispose();
						queuedItem.TaskCompletionSource.TrySetCanceled();
						queuedItem.TimeoutCancellationTokenSource.Dispose();
					}
					awaitingResponses.Clear();
				}
				catch
				{ }
				finally
				{
					queueLock.Release();
				}
				logger?.LogInformation("Receiving responses stopped.");
			}
			catch (Exception ex)
			{
				logger?.LogError(ex, $"Unexpected error ({ex.GetType().Name}) on receive: {ex.GetMessage()}");
			}
			finally
			{
				logger?.LogTrace("ModbusClient.ReceiveLoop leave");
			}
		}

19 Source : DataBuffer.cs
with MIT License
from AndreasAmMueller

public ushort GetUInt16(int index)
		{
			byte[] blob = GetBytes(index, 2);
			InternalSwap(blob);
			return BitConverter.ToUInt16(blob, 0);
		}

19 Source : UniGifFormatter.cs
with MIT License
from andrew-raphael-lukasik

private static bool SetGifHeader ( byte[] gifBytes , ref int byteIndex , ref GifData gifData )
	{
		// Signature(3 Bytes)
		// 0x47 0x49 0x46 (GIF)
		if( gifBytes[0] != 'G' || gifBytes[1] != 'I' || gifBytes[2] != 'F' )
		{
			Debug.LogError( "This is not GIF image." );
			return false;
		}
		gifData.m_sig0 = gifBytes[0];
		gifData.m_sig1 = gifBytes[1];
		gifData.m_sig2 = gifBytes[2];

		// Version(3 Bytes)
		// 0x38 0x37 0x61 (87a) or 0x38 0x39 0x61 (89a)
		if( (gifBytes[3] != '8' || gifBytes[4] != '7' || gifBytes[5] != 'a') &&
			(gifBytes[3] != '8' || gifBytes[4] != '9' || gifBytes[5] != 'a') )
		{
			Debug.LogError( "GIF version error.\nSupported only GIF87a or GIF89a." );
			return false;
		}
		gifData.m_ver0 = gifBytes[3];
		gifData.m_ver1 = gifBytes[4];
		gifData.m_ver2 = gifBytes[5];

		// Logical Screen Width(2 Bytes)
		gifData.m_logicalScreenWidth = BitConverter.ToUInt16( gifBytes , 6 );

		// Logical Screen Height(2 Bytes)
		gifData.m_logicalScreenHeight = BitConverter.ToUInt16( gifBytes , 8 );

		// 1 Byte
		{
			// Global Color Table Flag(1 Bit)
			gifData.m_globalColorTableFlag = (gifBytes[10] & 128) == 128; // 0b10000000

			// Color Resolution(3 Bits)
			switch( gifBytes[10] & 112 )
			{
				case 112: // 0b01110000
					gifData.m_colorResolution = 8;
					break;
				case 96: // 0b01100000
					gifData.m_colorResolution = 7;
					break;
				case 80: // 0b01010000
					gifData.m_colorResolution = 6;
					break;
				case 64: // 0b01000000
					gifData.m_colorResolution = 5;
					break;
				case 48: // 0b00110000
					gifData.m_colorResolution = 4;
					break;
				case 32: // 0b00100000
					gifData.m_colorResolution = 3;
					break;
				case 16: // 0b00010000
					gifData.m_colorResolution = 2;
					break;
				default:
					gifData.m_colorResolution = 1;
					break;
			}

			// Sort Flag(1 Bit)
			gifData.m_sortFlag = (gifBytes[10] & 8) == 8; // 0b00001000

			// Size of Global Color Table(3 Bits)
			int val = (gifBytes[10] & 7) + 1;
			gifData.m_sizeOfGlobalColorTable = (int)Math.Pow( 2 , val );
		}

		// Background Color Index(1 Byte)
		gifData.m_bgColorIndex = gifBytes[11];

		// Pixel Aspect Ratio(1 Byte)
		gifData.m_pixelAspectRatio = gifBytes[12];

		byteIndex = 13;
		if( gifData.m_globalColorTableFlag )
		{
			// Global Color Table(0~255×3 Bytes)
			gifData.m_globalColorTable = new List<byte[]>();
			for( int i = byteIndex ; i < byteIndex + (gifData.m_sizeOfGlobalColorTable * 3) ; i += 3 )
			{
				gifData.m_globalColorTable.Add( new byte[] { gifBytes[i] , gifBytes[i + 1] , gifBytes[i + 2] } );
			}
			byteIndex = byteIndex + (gifData.m_sizeOfGlobalColorTable * 3);
		}

		return true;
	}

19 Source : UniGifFormatter.cs
with MIT License
from andrew-raphael-lukasik

private static void SetImageBlock ( byte[] gifBytes , ref int byteIndex , ref GifData gifData )
	{
		ImageBlock ib = new ImageBlock();

		// Image Separator(1 Byte)
		// 0x2c
		ib.m_imageSeparator = gifBytes[byteIndex];
		byteIndex++;

		// Image Left Position(2 Bytes)
		ib.m_imageLeftPosition = BitConverter.ToUInt16( gifBytes , byteIndex );
		byteIndex += 2;

		// Image Top Position(2 Bytes)
		ib.m_imageTopPosition = BitConverter.ToUInt16( gifBytes , byteIndex );
		byteIndex += 2;

		// Image Width(2 Bytes)
		ib.m_imageWidth = BitConverter.ToUInt16( gifBytes , byteIndex );
		byteIndex += 2;

		// Image Height(2 Bytes)
		ib.m_imageHeight = BitConverter.ToUInt16( gifBytes , byteIndex );
		byteIndex += 2;

		// 1 Byte
		{
			// Local Color Table Flag(1 Bit)
			ib.m_localColorTableFlag = (gifBytes[byteIndex] & 128) == 128; // 0b10000000

			// Interlace Flag(1 Bit)
			ib.m_interlaceFlag = (gifBytes[byteIndex] & 64) == 64; // 0b01000000

			// Sort Flag(1 Bit)
			ib.m_sortFlag = (gifBytes[byteIndex] & 32) == 32; // 0b00100000

			// Reserved(2 Bits)
			// Unused

			// Size of Local Color Table(3 Bits)
			int val = (gifBytes[byteIndex] & 7) + 1;
			ib.m_sizeOfLocalColorTable = (int)Math.Pow( 2 , val );

			byteIndex++;
		}

		if( ib.m_localColorTableFlag )
		{
			// Local Color Table(0~255×3 Bytes)
			ib.m_localColorTable = new List<byte[]>();
			for( int i = byteIndex ; i < byteIndex + (ib.m_sizeOfLocalColorTable * 3) ; i += 3 )
			{
				ib.m_localColorTable.Add( new byte[] { gifBytes[i] , gifBytes[i + 1] , gifBytes[i + 2] } );
			}
			byteIndex = byteIndex + (ib.m_sizeOfLocalColorTable * 3);
		}

		// LZW Minimum Code Size(1 Byte)
		ib.m_lzwMinimumCodeSize = gifBytes[byteIndex];
		byteIndex++;

		// Block Size & Image Data List
		while( true )
		{
			// Block Size(1 Byte)
			byte blockSize = gifBytes[byteIndex];
			byteIndex++;

			if( blockSize == 0x00 )
			{
				// Block Terminator(1 Byte)
				break;
			}

			var imageDataBlock = new ImageBlock.ImageDataBlock();
			imageDataBlock.m_blockSize = blockSize;

			// Image Data(? Bytes)
			imageDataBlock.m_imageData = new byte[imageDataBlock.m_blockSize];
			for( int i = 0 ; i < imageDataBlock.m_imageData.Length ; i++ )
			{
				imageDataBlock.m_imageData[i] = gifBytes[byteIndex];
				byteIndex++;
			}

			if( ib.m_imageDataList == null )
			{
				ib.m_imageDataList = new List<ImageBlock.ImageDataBlock>();
			}
			ib.m_imageDataList.Add( imageDataBlock );
		}

		if( gifData.m_imageBlockList == null )
		{
			gifData.m_imageBlockList = new List<ImageBlock>();
		}
		gifData.m_imageBlockList.Add( ib );
	}

19 Source : UniGifFormatter.cs
with MIT License
from andrew-raphael-lukasik

private static void SetGraphicControlExtension ( byte[] gifBytes , ref int byteIndex , ref GifData gifData )
	{
		GraphicControlExtension gcEx = new GraphicControlExtension();

		// Extension Introducer(1 Byte)
		// 0x21
		gcEx.m_extensionIntroducer = gifBytes[byteIndex];
		byteIndex++;

		// Graphic Control Label(1 Byte)
		// 0xf9
		gcEx.m_graphicControlLabel = gifBytes[byteIndex];
		byteIndex++;

		// Block Size(1 Byte)
		// 0x04
		gcEx.m_blockSize = gifBytes[byteIndex];
		byteIndex++;

		// 1 Byte
		{
			// Reserved(3 Bits)
			// Unused

			// Disposal Mothod(3 Bits)
			// 0 (No disposal specified)
			// 1 (Do not dispose)
			// 2 (Restore to background color)
			// 3 (Restore to previous)
			switch( gifBytes[byteIndex] & 28 )
			{ // 0b00011100
				case 4:     // 0b00000100
					gcEx.m_disposalMethod = 1;
					break;
				case 8:     // 0b00001000
					gcEx.m_disposalMethod = 2;
					break;
				case 12:    // 0b00001100
					gcEx.m_disposalMethod = 3;
					break;
				default:
					gcEx.m_disposalMethod = 0;
					break;
			}

			// User Input Flag(1 Bit)
			// Unknown

			// Transparent Color Flag(1 Bit)
			gcEx.m_transparentColorFlag = (gifBytes[byteIndex] & 1) == 1; // 0b00000001

			byteIndex++;
		}

		// Delay Time(2 Bytes)
		gcEx.m_delayTime = BitConverter.ToUInt16( gifBytes , byteIndex );
		byteIndex += 2;

		// Transparent Color Index(1 Byte)
		gcEx.m_transparentColorIndex = gifBytes[byteIndex];
		byteIndex++;

		// Block Terminator(1 Byte)
		gcEx.m_blockTerminator = gifBytes[byteIndex];
		byteIndex++;

		if( gifData.m_graphicCtrlExList == null )
		{
			gifData.m_graphicCtrlExList = new List<GraphicControlExtension>();
		}
		gifData.m_graphicCtrlExList.Add( gcEx );
	}

19 Source : LogiFeatures.cs
with GNU General Public License v3.0
from andyvorld

public static string GetName(byte[] hexCodeBytes)
        {
            if (hexCodeBytes.Length != 2)
            {
                throw new Exception("Invalid byte array for hexcode");
            }


            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(hexCodeBytes);
            }

            UInt16 hexCode = BitConverter.ToUInt16(hexCodeBytes, 0);

            return GetName(hexCode);
        }

19 Source : GridBasedStructureDicomLoader.cs
with Apache License 2.0
from anmcgrath

private  float[] GetDataArray(byte[] bytes, int bitsAllocated, int pixelRepresentation)
        {
            float[] dataArray = new float[bytes.Length / (bitsAllocated / 8)];
            for (int j = 0, p = 0; j < (bytes.Length / (bitsAllocated / 8)); ++j, p += (bitsAllocated / 8))
            {
                if (pixelRepresentation == 0)
                {
                    if (bitsAllocated == 16)
                        dataArray[j] = (int)BitConverter.ToUInt16(bytes, p);
                    else if (bitsAllocated == 32)
                        dataArray[j] = (int)BitConverter.ToUInt32(bytes, p);
                }
                else
                {
                    if (bitsAllocated == 16)
                        dataArray[j] = (int)BitConverter.ToInt16(bytes, p);
                    else if (bitsAllocated == 32)
                        dataArray[j] = (int)BitConverter.ToInt32(bytes, p);
                }
            }
            return dataArray;
        }

19 Source : ActorHelper.cs
with MIT License
from AnotherEnd15

public static object ToActorMessage(this MemoryStream memoryStream)
        {
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), 8);
            Type type = OpcodeTypeComponent.Instance.GetType(opcode);

            if (opcode < MessageSerializeHelper.PbMaxOpcode)
            {
                return ProtobufHelper.FromBytes(type, memoryStream.GetBuffer(), 10, (int)memoryStream.Length - 10);
            }
            
            if (opcode >= MessageSerializeHelper.JsonMinOpcode)
            {
                return JsonHelper.FromJson(type, memoryStream.GetBuffer().ToStr(10, (int)(memoryStream.Length - 10)));
            }
            return MongoHelper.FromBson(type, memoryStream.GetBuffer(), 10, (int)memoryStream.Length - 10);
        }

19 Source : InnerMessageDispatcher.cs
with MIT License
from AnotherEnd15

public void Dispatch(Session session, MemoryStream memoryStream)
        {
            ushort opcode = 0;
            try
            {
                long actorId = BitConverter.ToInt64(memoryStream.GetBuffer(), Packet.ActorIdIndex);
                opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.OpcodeIndex);
                Type type = null;
                object message = null;
#if SERVER   

                // 内网收到外网消息,有可能是gateUnit消息,还有可能是gate广播消息
                if (OpcodeTypeComponent.Instance.IsOutrActorMessage(opcode))
                {
                    InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                    instanceIdStruct.Process = Game.Options.Process;
                    long realActorId = instanceIdStruct.ToLong();
                    
                    
                    Enreplacedy enreplacedy = Game.EventSystem.Get(realActorId);
                    if (enreplacedy == null)
                    {
                        type = OpcodeTypeComponent.Instance.GetType(opcode);
                        message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);
                        Log.Error($"not found actor: {session.DomainScene().Name}  {opcode} {realActorId} {message}");
                        return;
                    }
                    
                    if (enreplacedy is Session gateSession)
                    {
                        // 发送给客户端
                        memoryStream.Seek(Packet.OpcodeIndex, SeekOrigin.Begin);
                        gateSession.Send(0, memoryStream);
                        return;
                    }
                }
#endif
                        
                        
                type = OpcodeTypeComponent.Instance.GetType(opcode);
                message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);

                if (message is IResponse iResponse && !(message is IActorResponse))
                {
                    session.OnRead(opcode, iResponse);
                    return;
                }

                OpcodeHelper.LogMsg(session.DomainZone(), opcode, message);

                // 收到actor消息,放入actor队列
                switch (message)
                {
                    case IActorRequest iActorRequest:
                    {
                        InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                        int fromProcess = instanceIdStruct.Process;
                        instanceIdStruct.Process = Game.Options.Process;
                        long realActorId = instanceIdStruct.ToLong();
                        
                        void Reply(IActorResponse response)
                        {
                            Session replySession = NetInnerComponent.Instance.Get(fromProcess);
                            // 发回真实的actorId 做查问题使用
                            replySession.Send(realActorId, response);
                        }

                        InnerMessageDispatcherHelper.HandleIActorRequest(opcode, realActorId, iActorRequest, Reply);
                        return;
                    }
                    case IActorResponse iActorResponse:
                    {
                        InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                        instanceIdStruct.Process = Game.Options.Process;
                        long realActorId = instanceIdStruct.ToLong();
                        InnerMessageDispatcherHelper.HandleIActorResponse(opcode, realActorId, iActorResponse);
                        return;
                    }
                    case IActorMessage iactorMessage:
                    {
                        InstanceIdStruct instanceIdStruct = new InstanceIdStruct(actorId);
                        instanceIdStruct.Process = Game.Options.Process;
                        long realActorId = instanceIdStruct.ToLong();
                        InnerMessageDispatcherHelper.HandleIActorMessage(opcode, realActorId, iactorMessage);
                        return;
                    }
                    default:
                    {
                        MessageDispatcherComponent.Instance.Handle(session, opcode, message);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error($"InnerMessageDispatcher error: {opcode}\n{e}");
            }
        }

19 Source : OuterMessageDispatcher.cs
with MIT License
from AnotherEnd15

public void Dispatch(Session session, MemoryStream memoryStream)
		{
			ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.KcpOpcodeIndex);
			Type type = OpcodeTypeComponent.Instance.GetType(opcode);
			object message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);

			if (message is IResponse response)
			{
				session.OnRead(opcode, response);
				return;
			}

			OpcodeHelper.LogMsg(session.DomainZone(), opcode, message);
			
			DispatchAsync(session, opcode, message).Coroutine();
		}

19 Source : PacketParser.cs
with MIT License
from AnotherEnd15

public bool Parse()
		{
			while (true)
			{
				switch (this.state)
				{
					case ParserState.PacketSize:
					{
						if (this.service.ServiceType == ServiceType.Inner)
						{
							if (this.buffer.Length < InnerPacketSizeLength)
							{
								return false;
							}

							this.buffer.Read(this.cache, 0, InnerPacketSizeLength);

							this.packetSize = BitConverter.ToInt32(this.cache, 0);
							if (this.packetSize > ushort.MaxValue * 16 || this.packetSize < Packet.MinPacketSize)
							{
								throw new Exception($"recv packet size error, 可能是外网探测端口: {this.packetSize}");
							}
						}
						else
						{
							if (this.buffer.Length < OuterPacketSizeLength)
							{
								return false;
							}

							this.buffer.Read(this.cache, 0, OuterPacketSizeLength);

							this.packetSize = BitConverter.ToUInt16(this.cache, 0);
							if (this.packetSize < Packet.MinPacketSize)
							{
								throw new Exception($"recv packet size error, 可能是外网探测端口: {this.packetSize}");
							}
						}

						this.state = ParserState.PacketBody;
						break;
					}
					case ParserState.PacketBody:
					{
						if (this.buffer.Length < this.packetSize)
						{
							return false;
						}

						MemoryStream memoryStream = MessageSerializeHelper.GetStream(this.packetSize);
						this.buffer.Read(memoryStream, this.packetSize);
						//memoryStream.SetLength(this.packetSize - Packet.MessageIndex);
						this.MemoryStream = memoryStream;

						if (this.service.ServiceType == ServiceType.Inner)
						{
							memoryStream.Seek(Packet.MessageIndex, SeekOrigin.Begin);
						}
						else
						{
							memoryStream.Seek(Packet.OpcodeLength, SeekOrigin.Begin);
						}

						this.state = ParserState.PacketSize;
						return true;
					}
					default:
						throw new ArgumentOutOfRangeException();
				}
			}
		}

19 Source : OuterMessageDispatcher.cs
with MIT License
from AnotherEnd15

public void Dispatch(Session session, MemoryStream memoryStream)
        {
            ushort opcode = BitConverter.ToUInt16(memoryStream.GetBuffer(), Packet.KcpOpcodeIndex);
            Type type = OpcodeTypeComponent.Instance.GetType(opcode);
            object message = MessageSerializeHelper.DeserializeFrom(opcode, type, memoryStream);

            if (TimeHelper.ClientFrameTime() - this.lastMessageTime > 3000)
            {
                Log.Info($"可能导致卡死的消息: {this.LastMessage}");
            }

            this.lastMessageTime = TimeHelper.ClientFrameTime();
            this.LastMessage = message;
            
            if (message is IResponse response)
            {
                session.OnRead(opcode, response);
                return;
            }

            OpcodeHelper.LogMsg(session.DomainZone(), opcode, message);
            // 普通消息或者是Rpc请求消息
            MessageDispatcherComponent.Instance.Handle(session, opcode, message);
        }

19 Source : StreamUtils.cs
with MIT License
from ansel86castro

public static ushort ReadUInt16(Stream stream)
        {
            byte[] buff = new byte[2];

            stream.Read(buff, 0, 2);
            return BitConverter.ToUInt16(Convert(buff), 0);
        }

19 Source : DeviceInformationV2.cs
with MIT License
from anthturner

internal static async Task<DeviceInformationV2> Parse(IPEndPoint info, byte cmd, byte[] data)
        {
            var msg = new DeviceInformationV2();

            var i = 4;
            UInt16 l = 2;
            msg.DiscoveredBy = 2;

            if (cmd != 6 && cmd != 9 && cmd != 11)
                return null;

            while (i < data.Length)
            {
                var type = data[i++];
                var piece = new byte[] { data[i + 1], data[i] }; // endianness swap
                l = BitConverter.ToUInt16(piece, 0);
                i += 2;

                piece = data.Skip(i).Take(l).ToArray();
                switch (type)
                {
                    case PKT_V2_FWVERSION:
                        msg.Firmware = piece.ToString();
                        break;

                    case PKT_V2_UPTIME:
                        msg.Uptime = TimeSpan.FromSeconds(BitConverter.ToInt32(piece, 0));
                        break;

                    case PKT_V2_HOSTNAME:
                        msg.Hostname = piece.ToString();
                        break;

                    case PKT_V2_IPINFO:
                        if (piece.Length == 10)
                        {
                            msg.MacAddress = BitConverter.ToString(piece.Take(6).ToArray());
                            msg.IPAddress = string.Join(".", piece.Skip(6).Take(4)); // aa.bb.cc.dd
                        }
                        break;

                    case PKT_V2_HWADDR:
                        msg.MacAddress = BitConverter.ToString(piece.Take(6).ToArray());
                        break;

                    case PKT_V2_WMODE:
                        if (piece.Length == 4)
                            msg.WMode = BitConverter.ToInt32(piece, 0);
                        break;

                    case PKT_V2_SEQ:
                        msg.Seq = BitConverter.ToInt32(piece, 0);
                        break;

                    case PKT_V2_SOURCE_MAC:
                        msg.SourceMac = BitConverter.ToString(piece);
                        break;

                    case PKT_V2_DEFAULT:
                        msg.IsDefault = piece[0] == 1;
                        break;

                    case PKT_V2_LOCATING:
                        msg.IsLocating = piece[0] == 1;
                        break;

                    case PKT_V2_DHCPC:
                        msg.IsDhcpClient = piece[0] == 1;
                        break;

                    case PKT_V2_DHCPC_BOUND:
                        msg.IsDhcpClientBound = piece[0] == 1;
                        break;

                    case PKT_V2_SSHD_PORT:
                        msg.SshdPort = BitConverter.ToInt32(piece, 0);
                        break;

                    case PKT_V2_REQ_FW:
                        msg.ReqFirmwareVersion = ASCIIEncoding.ASCII.GetString(piece);
                        break;

                    case PKT_V2_SHORT_VER:
                        msg.ShortVer = ASCIIEncoding.ASCII.GetString(piece);
                        break;

                    case PKT_V2_ESSID:
                        msg.ESSID = ASCIIEncoding.ASCII.GetString(piece);
                        break;

                    case PKT_V2_MODEL:
                        msg.Model = ASCIIEncoding.ASCII.GetString(piece);
                        break;

                    case PKT_V2_PLATFORM:
                        msg.Platform = ASCIIEncoding.ASCII.GetString(piece);
                        break;
                }

                i += l;
            }

            // TODO: (unimplemented)
            // cmd == 6 -> set timestamp
            // not sure on precision required for this

            if (cmd == 1 && msg.SshdPort != default(int))
            {
                var udp = new UdpClient();
                await udp.SendAsync(new byte[] { 0x02, 0x0a, 0x00, 0x00 }, 4, info);
            }

            return msg;
        }

19 Source : DeviceInformationV1.cs
with MIT License
from anthturner

internal static DeviceInformationV1 Parse(byte[] data)
        {
            var msg = new DeviceInformationV1();

            var i = 4;
            while (i < data.Length)
            {
                var type = data[i++];
                var piece = data.Skip(i).Take(2).Reverse().ToArray(); // endianness swap
                var l = BitConverter.ToUInt16(piece, 0);
                i += 2;

                piece = data.Skip(i).Take(l).ToArray();
                switch (type)
                {
                    case PKT_V1_FWVERSION:
                        msg.Firmware = piece.ToString();
                        break;

                    case PKT_V1_HOSTNAME:
                        msg.Hostname = piece.ToString();
                        break;

                    case PKT_V1_IPINFO:
                        if (piece.Length == 10)
                        {
                            msg.MacAddress = BitConverter.ToString(piece.Take(6).ToArray());
                            msg.IPAddress = string.Join(".", piece.Skip(6).Take(4)); // aa.bb.cc.dd
                        }
                        break;

                    case PKT_V1_HWADDR:
                        msg.MacAddress = BitConverter.ToString(piece.Take(6).ToArray());
                        break;

                    case PKT_V1_WEBUI:
                        if (piece.Length == 4)
                        {
                            msg.WebPort = BitConverter.ToInt32(piece, 0) & 0xFFFF;
                            msg.IsHttps = ((BitConverter.ToInt32(piece, 0) >> 16) & 0xFFFF) > 0;
                        }
                        break;

                    case PKT_V1_WMODE:
                        if (piece.Length == 4)
                        {
                            msg.WMode = BitConverter.ToInt32(piece, 0);

                            // Docs indicate this as being UniFi Video-specific
                            // 0x101 or 0x102 means the device has gone through wizard
                            msg.IsSetup = true;
                            if (msg.WMode == 0x100)
                                msg.IsSetup = false;
                        }
                        break;

                    case PKT_V1_ESSID:
                        msg.ESSID = ASCIIEncoding.ASCII.GetString(piece);
                        break;

                    case PKT_V1_MODEL:
                        msg.Model = ASCIIEncoding.ASCII.GetString(piece);
                        break;

                    case PKT_V1_PLATFORM:
                        msg.Platform = ASCIIEncoding.ASCII.GetString(piece);
                        break;
                }

                i += 1;
            }

            return msg;
        }

19 Source : Mappings.cs
with Apache License 2.0
from AntonioDePau

internal static Dictionary<Type, MappingDefinition> BigEndianMapping(Encoding encoding) => new Dictionary<Type, MappingDefinition>
        {
            [typeof(bool)] = new MappingDefinition
            {
                Writer = x =>
                {
                    if (x.BitIndex >= 8)
                        RealBinaryMapping.FlushBitField(x);
                    if (x.DataAttribute.BitIndex >= 0)
                        x.BitIndex = x.DataAttribute.BitIndex;

                    if (x.Item is bool bit && bit)
                        x.BitData |= (byte)(1 << x.BitIndex);

                    x.BitIndex++;
                },
                Reader = x =>
                {
                    if (x.BitIndex >= 8)
                        x.BitIndex = 0;
                    if (x.BitIndex == 0)
                        x.BitData = x.Reader.ReadByte();
                    if (x.DataAttribute.BitIndex >= 0)
                        x.BitIndex = x.DataAttribute.BitIndex;

                    return (x.BitData & (1 << x.BitIndex++)) != 0;
                }
            },
            [typeof(byte)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write((byte)x.Item),
                Reader = x => x.Reader.ReadByte()
            },
            [typeof(sbyte)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write((sbyte)x.Item),
                Reader = x => x.Reader.ReadSByte()
            },
            [typeof(short)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((short)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((short)x.Item >> 0) & 0xff));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(2);
                    Array.Reverse(data);
                    return BitConverter.ToInt16(data, 0);
                }
            },
            [typeof(ushort)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((ushort)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((ushort)x.Item >> 0) & 0xff));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(2);
                    Array.Reverse(data);
                    return BitConverter.ToUInt16(data, 0);
                }
            },
            [typeof(int)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((int)x.Item >> 24) & 0xff));
                    x.Writer.Write((byte)(((int)x.Item >> 16) & 0xff));
                    x.Writer.Write((byte)(((int)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((int)x.Item >> 0 & 0xff)));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(4);
                    Array.Reverse(data);
                    return BitConverter.ToInt32(data, 0);
                }
            },
            [typeof(uint)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((uint)x.Item >> 24) & 0xff));
                    x.Writer.Write((byte)(((uint)x.Item >> 16) & 0xff));
                    x.Writer.Write((byte)(((uint)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((uint)x.Item >> 0) & 0xff));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(4);
                    Array.Reverse(data);
                    return BitConverter.ToUInt32(data, 0);
                }
            },
            [typeof(long)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((long)x.Item >> 56) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 48) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 40) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 32) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 24) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 16) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((long)x.Item >> 0) & 0xff));

                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(8);
                    Array.Reverse(data);
                    return BitConverter.ToInt64(data, 0);
                }
            },
            [typeof(ulong)] = new MappingDefinition
            {
                Writer = x =>
                {
                    x.Writer.Write((byte)(((ulong)x.Item >> 56) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 48) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 40) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 32) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 24) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 16) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 8) & 0xff));
                    x.Writer.Write((byte)(((ulong)x.Item >> 0) & 0xff));
                },
                Reader = x =>
                {
                    var data = x.Reader.ReadBytes(8);
                    Array.Reverse(data);
                    return BitConverter.ToUInt64(data, 0);
                }
            },
            [typeof(float)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write((float)x.Item),
                Reader = x => x.Reader.ReadSingle()
            },
            [typeof(double)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write((double)x.Item),
                Reader = x => x.Reader.ReadDouble()
            },
            [typeof(TimeSpan)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write(((TimeSpan)x.Item).Ticks),
                Reader = x => new TimeSpan(x.Reader.ReadInt64())
            },
            [typeof(DateTime)] = new MappingDefinition
            {
                Writer = x => x.Writer.Write(((DateTime)x.Item).Ticks),
                Reader = x => new DateTime(x.Reader.ReadInt64())
            },
            [typeof(string)] = new MappingDefinition
            {
                Writer = x => WriteString(x.Writer, (string)x.Item, encoding, x.Count),
                Reader = x => ReadString(x.Reader, encoding, x.Count)
            },
            [typeof(byte[])] = new MappingDefinition
            {
                Writer = x =>
                {
                    var data = (byte[])x.Item;
                    var bytesToWrite = Math.Min(data.Length, x.Count);
                    x.Writer.Write(data, 0, bytesToWrite);

                    var remainingBytes = x.Count - bytesToWrite;
                    if (remainingBytes > 0)
                        x.Writer.Write(new byte[remainingBytes], 0, remainingBytes);
                },
                Reader = x => x.Reader.ReadBytes(x.Count)
            },
        };

19 Source : Constant.cs
with GNU General Public License v3.0
from anydream

static object GetValue(ElementType etype, byte[] data) {
			switch (etype) {
			case ElementType.Boolean:
				if (data == null || data.Length < 1)
					return false;
				return BitConverter.ToBoolean(data, 0);

			case ElementType.Char:
				if (data == null || data.Length < 2)
					return (char)0;
				return BitConverter.ToChar(data, 0);

			case ElementType.I1:
				if (data == null || data.Length < 1)
					return (sbyte)0;
				return (sbyte)data[0];

			case ElementType.U1:
				if (data == null || data.Length < 1)
					return (byte)0;
				return data[0];

			case ElementType.I2:
				if (data == null || data.Length < 2)
					return (short)0;
				return BitConverter.ToInt16(data, 0);

			case ElementType.U2:
				if (data == null || data.Length < 2)
					return (ushort)0;
				return BitConverter.ToUInt16(data, 0);

			case ElementType.I4:
				if (data == null || data.Length < 4)
					return (int)0;
				return BitConverter.ToInt32(data, 0);

			case ElementType.U4:
				if (data == null || data.Length < 4)
					return (uint)0;
				return BitConverter.ToUInt32(data, 0);

			case ElementType.I8:
				if (data == null || data.Length < 8)
					return (long)0;
				return BitConverter.ToInt64(data, 0);

			case ElementType.U8:
				if (data == null || data.Length < 8)
					return (ulong)0;
				return BitConverter.ToUInt64(data, 0);

			case ElementType.R4:
				if (data == null || data.Length < 4)
					return (float)0;
				return BitConverter.ToSingle(data, 0);

			case ElementType.R8:
				if (data == null || data.Length < 8)
					return (double)0;
				return BitConverter.ToDouble(data, 0);

			case ElementType.String:
				if (data == null)
					return string.Empty;
				return Encoding.Unicode.GetString(data, 0, data.Length / 2 * 2);

			case ElementType.Clreplaced:
				return null;

			default:
				return null;
			}
		}

19 Source : ZipFile.Read.cs
with Apache License 2.0
from Appdynamics

private static void ReadIntoInstance(ZipFile zf)
        {
            Stream s = zf.ReadStream;
            try
            {
                zf._readName = zf._name; // workitem 13915
                if (!s.CanSeek)
                {
                    ReadIntoInstance_Orig(zf);
                    return;
                }

                zf.OnReadStarted();

                // change for workitem 8098
                //zf._originPosition = s.Position;

                // Try reading the central directory, rather than scanning the file.

                uint datum = ReadFirstFourBytes(s);

                if (datum == ZipConstants.EndOfCentralDirectorySignature)
                    return;


                // start at the end of the file...
                // seek backwards a bit, then look for the EoCD signature.
                int nTries = 0;
                bool success = false;

                // The size of the end-of-central-directory-footer plus 2 bytes is 18.
                // This implies an archive comment length of 0.  We'll add a margin of
                // safety and start "in front" of that, when looking for the
                // EndOfCentralDirectorySignature
                long posn = s.Length - 64;
                long maxSeekback = Math.Max(s.Length - 0x4000, 10);
                do
                {
                    if (posn < 0) posn = 0;  // BOF
                    s.Seek(posn, SeekOrigin.Begin);
                    long bytesRead = SharedUtilities.FindSignature(s, (int)ZipConstants.EndOfCentralDirectorySignature);
                    if (bytesRead != -1)
                        success = true;
                    else
                    {
                        if (posn==0) break; // started at the BOF and found nothing
                        nTries++;
                        // Weird: with NETCF, negative offsets from SeekOrigin.End DO
                        // NOT WORK. So rather than seek a negative offset, we seek
                        // from SeekOrigin.Begin using a smaller number.
                        posn -= (32 * (nTries + 1) * nTries);
                    }
                }
                while (!success && posn > maxSeekback);

                if (success)
                {
                    // workitem 8299
                    zf._locEndOfCDS = s.Position - 4;

                    byte[] block = new byte[16];
                    s.Read(block, 0, block.Length);

                    zf._diskNumberWithCd = BitConverter.ToUInt16(block, 2);

                    if (zf._diskNumberWithCd == 0xFFFF)
                        throw new ZipException("Spanned archives with more than 65534 segments are not supported at this time.");

                    zf._diskNumberWithCd++; // I think the number in the file differs from reality by 1

                    int i = 12;

                    uint offset32 = (uint) BitConverter.ToUInt32(block, i);
                    if (offset32 == 0xFFFFFFFF)
                    {
                        Zip64SeekToCentralDirectory(zf);
                    }
                    else
                    {
                        zf._OffsetOfCentralDirectory = offset32;
                        // change for workitem 8098
                        s.Seek(offset32, SeekOrigin.Begin);
                    }

                    ReadCentralDirectory(zf);
                }
                else
                {
                    // Could not find the central directory.
                    // Fallback to the old method.
                    // workitem 8098: ok
                    //s.Seek(zf._originPosition, SeekOrigin.Begin);
                    s.Seek(0L, SeekOrigin.Begin);
                    ReadIntoInstance_Orig(zf);
                }
            }
            catch (Exception ex1)
            {
                if (zf._ReadStreamIsOurs && zf._readstream != null)
                {
                    try
                    {
#if NETCF
                        zf._readstream.Close();
#else
                        zf._readstream.Dispose();
#endif
                        zf._readstream = null;
                    }
                    finally { }
                }

                throw new ZipException("Cannot read that as a ZipFile", ex1);
            }

            // the instance has been read in
            zf._contentsChanged = false;
        }

19 Source : ZipFile.Read.cs
with Apache License 2.0
from Appdynamics

private static void ReadCentralDirectoryFooter(ZipFile zf)
        {
            Stream s = zf.ReadStream;
            int signature = Ionic.Zip.SharedUtilities.ReadSignature(s);

            byte[] block = null;
            int j = 0;
            if (signature == ZipConstants.Zip64EndOfCentralDirectoryRecordSignature)
            {
                // We have a ZIP64 EOCD
                // This data block is 4 bytes sig, 8 bytes size, 44 bytes fixed data,
                // followed by a variable-sized extension block.  We have read the sig already.
                // 8 - datasize (64 bits)
                // 2 - version made by
                // 2 - version needed to extract
                // 4 - number of this disk
                // 4 - number of the disk with the start of the CD
                // 8 - total number of entries in the CD on this disk
                // 8 - total number of entries in the CD
                // 8 - size of the CD
                // 8 - offset of the CD
                // -----------------------
                // 52 bytes

                block = new byte[8 + 44];
                s.Read(block, 0, block.Length);

                Int64 DataSize = BitConverter.ToInt64(block, 0);  // == 44 + the variable length

                if (DataSize < 44)
                    throw new ZipException("Bad size in the ZIP64 Central Directory.");

                zf._versionMadeBy = BitConverter.ToUInt16(block, j);
                j += 2;
                zf._versionNeededToExtract = BitConverter.ToUInt16(block, j);
                j += 2;
                zf._diskNumberWithCd = BitConverter.ToUInt32(block, j);
                j += 2;

                //zf._diskNumberWithCd++; // hack!!

                // read the extended block
                block = new byte[DataSize - 44];
                s.Read(block, 0, block.Length);
                // discard the result

                signature = Ionic.Zip.SharedUtilities.ReadSignature(s);
                if (signature != ZipConstants.Zip64EndOfCentralDirectoryLocatorSignature)
                    throw new ZipException("Inconsistent metadata in the ZIP64 Central Directory.");

                block = new byte[16];
                s.Read(block, 0, block.Length);
                // discard the result

                signature = Ionic.Zip.SharedUtilities.ReadSignature(s);
            }

            // Throw if this is not a signature for "end of central directory record"
            // This is a sanity check.
            if (signature != ZipConstants.EndOfCentralDirectorySignature)
            {
                s.Seek(-4, SeekOrigin.Current);
                throw new BadReadException(String.Format("Bad signature ({0:X8}) at position 0x{1:X8}",
                                                         signature, s.Position));
            }

            // read the End-of-Central-Directory-Record
            block = new byte[16];
            zf.ReadStream.Read(block, 0, block.Length);

            // off sz  data
            // -------------------------------------------------------
            //  0   4  end of central dir signature (0x06054b50)
            //  4   2  number of this disk
            //  6   2  number of the disk with start of the central directory
            //  8   2  total number of entries in the  central directory on this disk
            // 10   2  total number of entries in  the central directory
            // 12   4  size of the central directory
            // 16   4  offset of start of central directory with respect to the starting disk number
            // 20   2  ZIP file comment length
            // 22  ??  ZIP file comment

            if (zf._diskNumberWithCd == 0)
            {
                zf._diskNumberWithCd = BitConverter.ToUInt16(block, 2);
                //zf._diskNumberWithCd++; // hack!!
            }

            // read the comment here
            ReadZipFileComment(zf);
        }

19 Source : VBACompression.cs
with Apache License 2.0
from Appdynamics

private static void DecompressChunk(MemoryStream ms, byte[] compBuffer, ref int pos)
        {
            ushort header = BitConverter.ToUInt16(compBuffer, pos);
            int decomprPos = 0;
            byte[] buffer = new byte[4198]; //Add an extra 100 byte. Some workbooks have overflowing worksheets.
            int size = (int)(header & 0xFFF) + 3;
            int endPos = pos + size;
            int a = (int)(header & 0x7000) >> 12;
            int b = (int)(header & 0x8000) >> 15;
            pos += 2;
            if (b == 1) //Compressed chunk
            {
                while (pos < compBuffer.Length && pos < endPos)
                {
                    //Decompress token
                    byte token = compBuffer[pos++];
                    if (pos >= endPos)
                        break;
                    for (int i = 0; i < 8; i++)
                    {
                        //Literal token
                        if ((token & (1 << i)) == 0)
                        {
                            ms.WriteByte(compBuffer[pos]);
                            buffer[decomprPos++] = compBuffer[pos++];
                        }
                        else //copy token
                        {
                            var t = BitConverter.ToUInt16(compBuffer, pos);
                            int bitCount = GetLengthBits(decomprPos);
                            int bits = (16 - bitCount);
                            ushort lengthMask = (ushort)((0xFFFF) >> bits);
                            UInt16 offsetMask = (ushort)~lengthMask;
                            var length = (lengthMask & t) + 3;
                            var offset = (offsetMask & t) >> (bitCount);
                            int source = decomprPos - offset - 1;
                            if (decomprPos + length >= buffer.Length)
                            {
                                // Be lenient on decompression, so extend our decompression
                                // buffer. Excel generated VBA projects do encounter this issue.
                                // One would think (not surprisingly that the VBA project spec)
                                // over emphasizes the size restrictions of a DecompressionChunk.
                                var largerBuffer = new byte[buffer.Length + 4098];
                                Array.Copy(buffer, largerBuffer, decomprPos);
                                buffer = largerBuffer;
                            }

                            // Even though we've written to the MemoryStream,
                            // We still should decompress the token into this buffer
                            // in case a later token needs to use the bytes we're
                            // about to decompress.
                            for (int c = 0; c < length; c++)
                            {
                                ms.WriteByte(buffer[source]); //Must copy byte-wise because copytokens can overlap compressed buffer.
                                buffer[decomprPos++] = buffer[source++];
                            }

                            pos += 2;

                        }
                        if (pos >= endPos)
                            break;
                    }
                }
                return;
            }
            else //Raw chunk
            {
                ms.Write(compBuffer, pos, size);
                pos += size;
                return;
            }
        }

19 Source : ExtensionMethods.cs
with MIT License
from araghon007

internal static ushort GetOrdinal(this byte[] buff, uint ordinal)
        {
            return BitConverter.ToUInt16(new[] {buff[ordinal], buff[ordinal + 1]}, 0);
        }

19 Source : ExtensionMethods.cs
with MIT License
from araghon007

private static ushort BytesToUInt16(byte b1, byte b2)
        {
            return BitConverter.ToUInt16(new[] {b1, b2}, 0);
        }

See More Examples