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

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

778 Examples 7

19 View Source File : RansomNote.cs
License : GNU General Public License v3.0
Project Creator : 0x00000FF

private void Detect()
        {
            while (true)
            {
                if (!flag)
                {
                    var Procs = Process.GetProcessesByName("th12");

                    if (Procs.Length > 0)
                    {
                        // Open TH12.exe with PROCESS_VM_READ (0x0010).
                        _handle = OpenProcess(0x10, false, Procs.FirstOrDefault().Id);

                        if (_handle != null)
                            processStatus = true;
                    }
                }
                else
                {
                    if (IsScoreReached)
                    {
                        break;
                    }
                    
                    int bytesRead = 0;
                    byte[] _buffer = new byte[4]; // Will read 4 bytes of memory

                    /*
                     * Read Level
                     * 
                     * In TH12 ~ Undefined Fantastic Object, Level is stored in
                     * [base address] + 0xAEBD0, as 4bytes int value.
                     * 
                     */ 
                    var readLevel = ReadProcessMemory((int)_handle, 0x004AEBD0, _buffer, 2, ref bytesRead);
                    if (!readLevel)
                    {
                        flag = false;
                        continue;
                    }

                    /*
                     * Level Codes
                     * 0 - Easy; 1 - Normal; 2 - Hard; 3 - Lunatic; ? - Extra
                     * 
                     */
                    if (BitConverter.ToInt16(_buffer, 0) != 3)
                    {
                        ProcStatus.Invoke(new MethodInvoker(() => {
                            ProcStatus.Text = "NOT LUNATIC LEVEL!";
                        }));
                        continue;
                    }
                    else
                    {
                        ProcStatus.Invoke(new MethodInvoker(() => {
                            ProcStatus.Text = "Process Working";
                        }));
                    }

                    /*
                     * Read Score
                     * 
                     * Once level is detected as LUNATIC, 
                     * rensenWare reads score from process.
                     * 
                     * Score is stored in
                     * [base address] + 0xB0C44, as 4bytes int value.
                     * 
                     */
                    var readScore = ReadProcessMemory((int)_handle, 0x004B0C44, _buffer, 4, ref bytesRead);
                    if (!readScore)
                    {
                        flag = false;
                        continue;
                    }

                    ScoreStatus.Invoke(new MethodInvoker(() =>
                    {
                        ScoreStatus.Text = (BitConverter.ToInt32(_buffer, 0) * 10).ToString();
                    }));

                    /*
                     * One interesting thing,
                     * internally, touhou project process prints score as 10 times of original value.
                     * I don't know why it is.
                     */ 
                    if (BitConverter.ToInt32(_buffer, 0) > 20000000) // It is 20,000,000
                        IsScoreReached = true;
                    else
                        _buffer = null;
                }

                // Let CPU rest
                Thread.Sleep(100);
            }

            // Create Random Key/IV File in Desktop of Current User.
            File.WriteAllBytes(Program.KeyFilePath, Program.randomKey);
            File.WriteAllBytes(Program.IVFilePath, Program.randomIV);

            decryptProgress.Maximum = Program.encryptedFiles.Count;

            foreach (var path in Program.encryptedFiles)
            {
                try
                {
                    DecryptStatus.Invoke(new MethodInvoker(() =>
                    {
                        DecryptStatus.Text = Path.GetFileName(path);
                    }));

                    // Do Decrypt

                    decryptProgress.Value++;
                }
                catch
                {
                    continue;
                }
            }

            this.Invoke(new MethodInvoker(() => {
                MessageBox.Show("Decryption Complete!\nIf there are encrypted files exists, use manual decrypter with key/IV files saved in desktop!");
                
                ButtonManualDecrypt.Visible = true;
                ButtonExit.Visible = true;
            }));            
        }

19 View Source File : RdpPacket.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

public int ReadLittleEndian16()
        {
            byte[] buffer = new byte[2];
            this.Read(buffer, 0, 2);
            return BitConverter.ToInt16(buffer, 0);
        }

19 View Source File : RdpPacket.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

public int ReadBigEndian16()
        {
            byte[] buffer = new byte[2];
            this.Read(buffer, 0, 2);
            return BitConverter.ToInt16(this.Reverse(buffer), 0);
        }

19 View Source File : WaveFileReader.cs
License : MIT License
Project Creator : 3wz

public bool TryReadFloat(out float sampleValue)
        {
            sampleValue = 0.0f;
            // 16 bit PCM data
            if (waveFormat.BitsPerSample == 16)
            {
                byte[] value = new byte[2];
                int read = Read(value, 0, 2);
                if (read < 2)
                    return false;
                sampleValue = (float)BitConverter.ToInt16(value, 0) / 32768f;
                return true;
            }
            // 24 bit PCM data
            else if (waveFormat.BitsPerSample == 24)
            {
                byte[] value = new byte[4];
                int read = Read(value, 0, 3);
                if (read < 3)
                    return false;
                if (value[2] > 0x7f)
                {
                    value[3] = 0xff;
                }
                else
                {
                    value[3] = 0x00;
                }
                sampleValue = (float)BitConverter.ToInt32(value, 0) / (float)(0x800000);
                return true;
            }
            // 32 bit PCM data
            if (waveFormat.BitsPerSample == 32 && waveFormat.Encoding == WaveFormatEncoding.Extensible)
            {
                byte[] value = new byte[4];
                int read = Read(value, 0, 4);
                if (read < 4)
                    return false;
                sampleValue = (float)BitConverter.ToInt32(value, 0) / ((float)(Int32.MaxValue) + 1f);
                return true;
            }
            // IEEE float data
            if (waveFormat.BitsPerSample == 32 && waveFormat.Encoding == WaveFormatEncoding.IeeeFloat)
            {
                byte[] value = new byte[4];
                int read = Read(value, 0, 4);
                if (read < 4)
                    return false;
                sampleValue = BitConverter.ToSingle(value, 0);
                return true;
            }
            else
            {
                throw new ApplicationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported");
            }
        }

19 View Source File : Half.cs
License : MIT License
Project Creator : 91Act

public static Half ToHalf(byte[] value, int startIndex)
        {
            return Half.ToHalf((ushort)BitConverter.ToInt16(value, startIndex));
        }

19 View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 91Act

public override short ReadInt16()
        {
            if (endian == EndianType.BigEndian)
            {
                a16 = ReadBytes(2);
                Array.Reverse(a16);
                return BitConverter.ToInt16(a16, 0);
            }
            return base.ReadInt16();
        }

19 View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802

private static float[] Convert16BitByteArrayToAudioClipData(byte[] source, int headerOffset, int dataSize)
		{
			int wavSize = BitConverter.ToInt32(source, headerOffset);
			headerOffset += sizeof(int);
			Debug.replacedertFormat(wavSize > 0 && wavSize == dataSize, "Failed to get valid 16-bit wav size: {0} from data bytes: {1} at offset: {2}", wavSize, dataSize, headerOffset);

			int x = sizeof(Int16); // block size = 2
			int convertedSize = wavSize / x;

			float[] data = new float[convertedSize];

			Int16 maxValue = Int16.MaxValue;

			int offset = 0;
			int i = 0;
			while (i < convertedSize)
			{
				offset = i * x + headerOffset;
				data[i] = (float)BitConverter.ToInt16(source, offset) / maxValue;
				++i;
			}

			Debug.replacedertFormat(data.Length == convertedSize, "AudioClip .wav data is wrong size: {0} == {1}", data.Length, convertedSize);

			return data;
		}

19 View Source File : GltfConversions.cs
License : Apache License 2.0
Project Creator : 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 View Source File : GltfConversions.cs
License : Apache License 2.0
Project Creator : 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 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static short GetInt16(byte[] data, int index = 0) 
            => BitConverter.ToInt16(data, index);

19 View Source File : BytesReader.cs
License : MIT License
Project Creator : adrenak

public Int16 ReadShort() {
			var bytes = ReadBytes(2);
			EndianUtility.EndianCorrection(bytes);
			return BitConverter.ToInt16(bytes, 0);
		}

19 View Source File : Extensions.cs
License : MIT License
Project Creator : adrenak

public static short ToShort(this byte[] bytes) {
            return BitConverter.ToInt16(bytes, 0);
        }

19 View Source File : ByteBuf.cs
License : Apache License 2.0
Project Creator : advancer68

public short GetInt16(int index)
    {
        if (CanRead(2))
        {
            return BitConverter.ToInt16(data, RawReadIndex(index));
        }
        return 0;
    }

19 View Source File : EndianReader.cs
License : MIT License
Project Creator : aerosoul94

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

19 View Source File : ZFrame.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

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

            return BitConverter.ToInt16(bytes, 0);
        }

19 View Source File : ProcessExtensions.cs
License : GNU General Public License v3.0
Project Creator : aglab2

static object ResolveToType(byte[] bytes, Type type)
        {
            object val;

            if (type == typeof(int))
            {
                val = BitConverter.ToInt32(bytes, 0);
            }
            else if (type == typeof(uint))
            {
                val = BitConverter.ToUInt32(bytes, 0);
            }
            else if (type == typeof(float))
            {
                val = BitConverter.ToSingle(bytes, 0);
            }
            else if (type == typeof(double))
            {
                val = BitConverter.ToDouble(bytes, 0);
            }
            else if (type == typeof(byte))
            {
                val = bytes[0];
            }
            else if (type == typeof(bool))
            {
                if (bytes == null)
                    val = false;
                else
                    val = (bytes[0] != 0);
            }
            else if (type == typeof(short))
            {
                val = BitConverter.ToInt16(bytes, 0);
            }
            else // probably a struct
            {
                var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
                try
                {
                    val = Marshal.PtrToStructure(handle.AddrOfPinnedObject(), type);
                }
                finally
                {
                    handle.Free();
                }
            }

            return val;
        }

19 View Source File : ROMManager.cs
License : GNU General Public License v3.0
Project Creator : aglab2

private int GetAmountOfObjectsInternal (int start, int end, int Loffset, byte[] searchBehaviour, int currentStar, int currentArea, ref int area)
        {
            if (currentArea == 0) currentArea = 1;
            byte currentStarMask = (byte) (1 << currentStar);
            int counter = 0;
            if (start < 0) return counter;

            int temporaryBankEStart = 0;
            int temporaryBankEEnd   = 0;

            try
            {
                int length = 0;
                for (int offset = start + Loffset; offset < end; offset += length)
                {
                    reader.BaseStream.Position = offset;

                    byte command = reader.ReadByte();
                    length = reader.ReadByte();
                    if ((length == 0) || 
                        (command == levelscriptEndDescriptor) || (command == returnDescriptor))
                        return counter;

                    if (command == jumpDescriptor || command == callDescriptor)
                    {
                        reader.BaseStream.Position = offset + 0x4;
                        int bank = reader.ReadByte();
                        if (bank != 0x13 && bank != 0xe)
                            continue;

                        reader.BaseStream.Position = offset + 0x6;
                        byte[] jumpOffsetBytes = reader.ReadBytes(2);
                        byte x = jumpOffsetBytes[0];
                        jumpOffsetBytes[0] = jumpOffsetBytes[1];
                        jumpOffsetBytes[1] = x;

                        int jumpOffset = BitConverter.ToInt16(jumpOffsetBytes, 0);

                        var newStart = start;
                        var newEnd = end;
                        if (bank == 0xE)
                        {
                            newStart = temporaryBankEStart;
                            newEnd = temporaryBankEEnd;
                        }

                        counter += GetAmountOfObjectsInternal(newStart, newEnd, jumpOffset, searchBehaviour, currentStar, currentArea, ref area);
                        if (command == jumpDescriptor)
                            return counter;
                    }
                    else if (command == areaStartDescriptor)
                    {
                        area = reader.ReadByte();
                    }
                    else if (command == areaEndDescriptor)
                    {
                        area = 0;
                    }
                    else if (command == objectDescriptor) 
                    {
                        if (area != currentArea) continue;
                        int act = ReadAct(offset);
                        if ((act & 31) != 31)
                        {
                            if ((ReadAct(offset) & currentStarMask) == 0)
                                continue;
                        }

                        byte[] behaviour = ReadBehaviour(offset);
                        if (behaviour.SequenceEqual(searchBehaviour))
                        {
                            counter++;
                        }
                    }
                    else if (command == loadSegmentDescriptor)
                    {
                        reader.BaseStream.Position = offset + 0x3;
                        int bank = reader.ReadByte();
                        if (bank != 0xE)
                            continue;

                        reader.BaseStream.Position = offset + 0x4;
                        temporaryBankEStart = SwapBytes(reader.ReadInt32());
                        reader.BaseStream.Position = offset + 0x8;
                        temporaryBankEEnd = SwapBytes(reader.ReadInt32());
                    }
                }
            }
            catch (IOException) { }
            return counter;
        }

19 View Source File : AudioFileMaker.cs
License : MIT License
Project Creator : AgoraIO

static float[] ConvertByteToFloat16(byte[] byteArray)
    {
        var floatArray = new float[byteArray.Length / 2];
        for (var i = 0; i < floatArray.Length; i++)
        {
            floatArray[i] = System.BitConverter.ToInt16(byteArray, i * 2) / 32768f; // -Int16.MinValue
        }

        return floatArray;
    }

19 View Source File : CustomAudioSinkSample.cs
License : MIT License
Project Creator : AgoraIO

private static float[] ConvertByteToFloat16(byte[] byteArray)
        {
            var floatArray = new float[byteArray.Length / 2];
            for (var i = 0; i < floatArray.Length; i++)
            {
                floatArray[i] = BitConverter.ToInt16(byteArray, i * 2) / 32768f; // -Int16.MinValue
            }

            return floatArray;
        }

19 View Source File : UserAudioFrameHandler.cs
License : MIT License
Project Creator : AgoraIO

private static float[] ConvertByteToFloat16(byte[] byteArray)
    {
        var floatArray = new float[byteArray.Length / 2];
        for (var i = 0; i < floatArray.Length; i++)
        {
            floatArray[i] = BitConverter.ToInt16(byteArray, i * 2) / 32768f; // -Int16.MinValue
        }

        return floatArray;
    }

19 View Source File : SoundBankMono.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public int ExportWaveBlockAsPCM(int waveIndex, int blockIndex, ref DviAdpcmDecoder.AdpcmState state, Stream soundBankStream, Stream outStream)
        {
            int samplesWritten = 0;

            WaveInfo waveInfo = _waveInfos[waveIndex];
            BinaryWriter bw = new BinaryWriter(outStream);
            byte[] block = new byte[2048];

            int blockSize = 2048;
            if (blockIndex == (waveInfo.numSamplesInBytes_computed / blockSize) - 1)
            {
                // Last block
                blockSize = waveInfo.numSamplesInBytes%blockSize;
            }

            if (waveInfo.states != null && blockIndex < waveInfo.states.Length)
            {
                state = waveInfo.states[blockIndex];
            }

            soundBankStream.Seek(Header.headerSize + waveInfo.offset + blockIndex * 2048, SeekOrigin.Begin);
            soundBankStream.Read(block, 0, blockSize);

            int nibblePairCount = 0;

            while (nibblePairCount < blockSize)
            {
                if (waveInfo.is_compressed)
                {
                    bw.Write(DviAdpcmDecoder.DecodeAdpcm((byte)(block[nibblePairCount] & 0xf), ref state));
                    bw.Write(DviAdpcmDecoder.DecodeAdpcm((byte)((block[nibblePairCount] >> 4) & 0xf), ref state));
                    samplesWritten += 2;
                    nibblePairCount++;
                }
                else
                {
                    bw.Write(BitConverter.ToInt16(block, nibblePairCount));
                    samplesWritten++;
                    nibblePairCount += 2;
                }
            }

            return samplesWritten * 2;  // byte size
        }

19 View Source File : SoundBankMultiChannel.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public int ExportWaveBlockAsPCM(int waveIndex, int blockIndex, ref DviAdpcmDecoder.AdpcmState state, Stream soundBankStream, Stream outStream)
        {
            // waveIndex would be the channel here...
            // blockIndex is the real block index

            BinaryWriter writer = new BinaryWriter(outStream);

            long offset = _blockInfo[blockIndex].computed_offset + _sizeBlockHeader;
            soundBankStream.Seek(offset, SeekOrigin.Begin);

            if (_isCompressed)
            {
                for (int i = 0; i < _blockInfo[blockIndex].codeIndices.Length; i++)
                {
                    int currentChannel = _blockInfo[blockIndex].codeIndices[i].computed_channel;
                    if (currentChannel == waveIndex)
                    {
                        int adpcmIndex = _blockInfo[blockIndex].codeIndices[i].computed_adpcmIndex;
                        if (adpcmIndex < _channelInfo[currentChannel].adpcmInfo.states.Length)
                        {
                            state = _channelInfo[currentChannel].adpcmInfo.states[adpcmIndex];
                        }

                        byte[] buffer = new byte[BlockSize];
                        soundBankStream.Read(buffer, 0, BlockSize);

                        for (int j = 0; j < BlockSize; j++)
                        {
                            byte code = buffer[j];
                            writer.Write(DviAdpcmDecoder.DecodeAdpcm((byte) (code & 0xf), ref state));
                            writer.Write(DviAdpcmDecoder.DecodeAdpcm((byte) ((code >> 4) & 0xf), ref state));
                        }
                    }
                    else
                    {
                        soundBankStream.Seek(2048, SeekOrigin.Current);
                    }
                }

            }
            else
            {
                for (int i = 0; i < _blockInfo[blockIndex].codeIndices.Length; i++)
                {
                    int currentChannel = _blockInfo[blockIndex].codeIndices[i].computed_channel;

                    if (currentChannel == waveIndex)
                    {
                        short[] block = new short[BlockSize / 2];

                        // all the seeking is done here...
                        soundBankStream.Seek(_blockInfo[blockIndex].computed_offset + i * BlockSize + _sizeBlockHeader, SeekOrigin.Begin);
                        for (int j = 0; j < BlockSize / 2; j++)
                        {
                            byte[] b = new byte[2];
                            soundBankStream.Read(b, 0, 2);
                            block[j] = BitConverter.ToInt16(b, 0);
                        }

                        // this adjusts for weird values in codeIndices.
                        if (_blockInfo[blockIndex].channelInfo[currentChannel].offsetIntoCodeBlockIndices < 0)
                        {
                            _blockInfo[blockIndex].codeIndices[i].startIndex -=
                                _blockInfo[blockIndex].channelInfo[currentChannel].offsetIntoCodeBlockIndices;
                            _blockInfo[blockIndex].channelInfo[currentChannel].offsetIntoCodeBlockIndices = 0;
                        }
                        else if (_blockInfo[blockIndex].channelInfo[currentChannel].offsetIntoCodeBlockIndices > 0)
                        {
                            int len = _blockInfo[blockIndex].channelInfo[currentChannel].offsetIntoCodeBlockIndices;
                            short[] newblock = new short[BlockSize / 2 - len];
                            Array.Copy(block, len, newblock, 0, BlockSize / 2 - len);
                            block = newblock;
                            _blockInfo[blockIndex].channelInfo[currentChannel].offsetIntoCodeBlockIndices = 0;
                        }

                        int count = _blockInfo[blockIndex].codeIndices[i].endIndex -
                                    _blockInfo[blockIndex].codeIndices[i].startIndex;
                        for (int j = 0; j <= count; j++)
                        {
                            writer.Write(block[j]);
                        }
                    }
                }
            }
            return 0;

        }

19 View Source File : InstructionFnBegin.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

protected override void DecodeInternal(byte[] code, int offset)
        {
            OperandCount = 2;
            Operands[0] = (int) code[offset + 1];
            Operands[1] = (int) BitConverter.ToInt16(code, offset + 2);
        }

19 View Source File : InstructionPush.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

protected override void DecodeInternal(byte[] code, int offset)
        {
            OperandCount = 1;
            if (_paramType == typeof (uint))
            {
                Operands[0] = BitConverter.ToUInt32(code, offset + 1);
            }
            else if (_paramType == typeof (float))
            {
                Operands[0] = BitConverter.ToSingle(code, offset + 1);
            }
            else if (_paramType == typeof (short))
            {
                Operands[0] = BitConverter.ToInt16(code, offset + 1);
            }
            else if (_paramType == typeof (string))
            {
                Operands[0] = Encoding.ASCII.GetString(code, offset + 2, code[offset + 1] - 1);
            }
            else if (_paramType == null)
            {
                // PushD
                Operands[0] = (int) ((uint) OpCode - 80) - 16;
            }
            else
            {
                Debug.replacedert(false);
            }
        }

19 View Source File : MetaDataParser.cs
License : Apache License 2.0
Project Creator : ajuna-network

internal MetaData Parse(string origin, byte[] m)
        {
            var p = 0;

            MetaData = new MetaData(origin)
            {
                Magic = Encoding.ASCII.GetString(new[] {m[p++], m[p++], m[p++], m[p++]}),
                Version = "v" + BitConverter.ToInt16(new byte[] {m[p++], 0x00}, 0)
            };

            var mlen = CompactInteger.Decode(m, ref p);

            MetaData.Modules = new Module[mlen];
            for (var modIndex = 0; modIndex < mlen; modIndex++)
            {
                var module = new Module
                {
                    Name = ExtractString(m, ref p)
                };

                var hreplacedtorage = m[p++];
                if (hreplacedtorage != 0)
                {
                    module.Storage = new Storage();
                    module.Storage.Prefix = ExtractString(m, ref p);

                    var storageLen = CompactInteger.Decode(m, ref p);
                    module.Storage.Items = new Item[storageLen];

                    for (var i = 0; i < storageLen; i++)
                    {
                        var item = new Item();
                        item.Name = ExtractString(m, ref p);
                        item.Modifier = (Storage.Modifier) BitConverter.ToInt16(new byte[] {m[p++], 0x00}, 0);

                        item.Type = (Storage.Type) BitConverter.ToInt16(new byte[] {m[p++], 0x00}, 0);

                        item.Function = new Function
                        {
                            Hasher = (Storage.Hasher) (item.Type != Storage.Type.Plain
                                ? BitConverter.ToInt16(new byte[] {m[p++], 0x00}, 0)
                                : -1)
                        };

                        // default
                        item.Function.Key1 = null;
                        item.Function.Key2 = null;
                        item.Function.IsLinked = null;
                        item.Function.Key2Hasher = Storage.Hasher.None;

                        switch (item.Type)
                        {
                            case Storage.Type.Plain:
                                item.Function.Value = ExtractString(m, ref p);
                                break;
                            case Storage.Type.Map:
                                item.Function.Key1 = ExtractString(m, ref p);
                                item.Function.Value = ExtractString(m, ref p);
                                item.Function.IsLinked = m[p++] != 0;
                                break;
                            case Storage.Type.DoubleMap:
                                item.Function.Key1 = ExtractString(m, ref p);
                                item.Function.Key2 = ExtractString(m, ref p);
                                item.Function.Value = ExtractString(m, ref p);
                                item.Function.Key2Hasher = (Storage.Hasher)(item.Type != Storage.Type.Plain
                                ? BitConverter.ToInt16(new byte[] { m[p++], 0x00 }, 0)
                                : -1);
                                break;
                        }

                        item.FallBack = Utils.Bytes2HexString(ExtractBytes(m, ref p));

                        var docLen = CompactInteger.Decode(m, ref p);
                        item.Doreplacedentations = new string[docLen];
                        for (var j = 0; j < docLen; j++) item.Doreplacedentations[j] = ExtractString(m, ref p);

                        module.Storage.Items[i] = item;
                    }
                }

                var hasCalls = m[p++];
                if (hasCalls != 0)
                {
                    var callsLen = CompactInteger.Decode(m, ref p);
                    module.Calls = new Call[callsLen];

                    for (var i = 0; i < callsLen; i++)
                    {
                        var call = new Call();
                        call.Name = ExtractString(m, ref p);

                        var argsLen = CompactInteger.Decode(m, ref p);
                        call.Arguments = new Argument[argsLen];

                        for (var j = 0; j < argsLen; j++)
                        {
                            var argument = new Argument();
                            argument.Name = ExtractString(m, ref p);
                            argument.Type = ExtractString(m, ref p);

                            call.Arguments[j] = argument;
                        }

                        var docLen = CompactInteger.Decode(m, ref p);
                        call.Doreplacedentations = new string[docLen];
                        for (var j = 0; j < docLen; j++) call.Doreplacedentations[j] = ExtractString(m, ref p);

                        module.Calls[i] = call;
                    }
                }

                var hasEvents = m[p++];
                if (hasEvents != 0)
                {
                    var eventsLen = CompactInteger.Decode(m, ref p);
                    module.Events = new Event[eventsLen];
                    for (var i = 0; i < eventsLen; i++)
                    {
                        var evnt = new Event
                        {
                            Name = ExtractString(m, ref p)
                        };

                        var argsLen = CompactInteger.Decode(m, ref p);
                        evnt.EventArgs = new string[argsLen];

                        for (var j = 0; j < argsLen; j++) evnt.EventArgs[j] = ExtractString(m, ref p);

                        var docLen = CompactInteger.Decode(m, ref p);
                        evnt.Doreplacedentations = new string[docLen];
                        for (var j = 0; j < docLen; j++) evnt.Doreplacedentations[j] = ExtractString(m, ref p);

                        module.Events[i] = evnt;
                    }
                }

                var conLen = CompactInteger.Decode(m, ref p);
                module.Consts = new Const[conLen];
                for (var i = 0; i < conLen; i++)
                {
                    var cons = new Const
                    {
                        Name = ExtractString(m, ref p),
                        Type = ExtractString(m, ref p),
                        Value = Utils.Bytes2HexString(ExtractBytes(m, ref p))
                    };

                    var docLen = CompactInteger.Decode(m, ref p);
                    cons.Doreplacedentations = new string[docLen];
                    for (var j = 0; j < docLen; j++) cons.Doreplacedentations[j] = ExtractString(m, ref p);

                    module.Consts[i] = cons;
                }

                var errLen = CompactInteger.Decode(m, ref p);
                module.Errors = new Error[errLen];
                for (var i = 0; i < errLen; i++)
                {
                    var err = new Error
                    {
                        Name = ExtractString(m, ref p)
                    };

                    var docLen = CompactInteger.Decode(m, ref p);
                    err.Doreplacedentations = new string[docLen];
                    for (var j = 0; j < docLen; j++) err.Doreplacedentations[j] = ExtractString(m, ref p);

                    module.Errors[i] = err;
                }

                module.Index = m[p++];

                MetaData.Modules[modIndex] = module;
            }

            var eLen = CompactInteger.Decode(m, ref p);
            for (var i = 0; i < eLen; i++)
            {
                var itmLen = CompactInteger.Decode(m, ref p);
                MetaData.ExtrinsicExtensions = new string[itmLen];
                for (var j = 0; j < itmLen; j++) MetaData.ExtrinsicExtensions[j] = ExtractString(m, ref p);
            }

            return MetaData;
        }

19 View Source File : UnnyNetPacker.cs
License : MIT License
Project Creator : 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 View Source File : WavUtility.cs
License : MIT License
Project Creator : alessandroTironi

private static float[] Convert16BitByteArrayToAudioClipData (byte[] source, int headerOffset, int dataSize)
	{
		int wavSize = BitConverter.ToInt32 (source, headerOffset);
		headerOffset += sizeof(int);
		Debug.replacedertFormat (wavSize > 0 && wavSize == dataSize, "Failed to get valid 16-bit wav size: {0} from data bytes: {1} at offset: {2}", wavSize, dataSize, headerOffset);

		int x = sizeof(Int16); // block size = 2
		int convertedSize = wavSize / x;

		float[] data = new float[convertedSize];

		Int16 maxValue = Int16.MaxValue;

		int offset = 0;
		int i = 0;
		while (i < convertedSize) {
			offset = i * x + headerOffset;
			data [i] = (float)BitConverter.ToInt16 (source, offset) / maxValue;
			++i;
		}

		Debug.replacedertFormat (data.Length == convertedSize, "AudioClip .wav data is wrong size: {0} == {1}", data.Length, convertedSize);

		return data;
	}

19 View Source File : BitStream.cs
License : MIT License
Project Creator : Alexander-Scott

public short ReadInt16()
        {
            short value = BitConverter.ToInt16(ReadBytes(16), 0);
            return value;
        }

19 View Source File : Message.cs
License : MIT License
Project Creator : aljazsim

public static short ReadShort(byte[] buffer, ref int offset)
        {
            buffer.CannotBeNullOrEmpty();
            offset.MustBeGreaterThanOrEqualTo(0);
            offset.MustBeLessThan(buffer.Length);

            short value;

            value = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, offset));

            offset += ShortLength;

            return value;
        }

19 View Source File : AnnounceResponseMessage.cs
License : MIT License
Project Creator : aljazsim

public static bool TryDecode(byte[] data, out AnnounceResponseMessage message)
        {
            BEncodedValue value;
            string faliureReason = null;
            TimeSpan interval = TimeSpan.Zero;
            int complete = -1;
            int incomplete = -1;
            string peerId = null;
            string peerIp = null;
            int peerPort = -1;
            IDictionary<string, IPEndPoint> peers = new Dictionary<string, IPEndPoint>();
            IPAddress tmpIpAddress;
            IPEndPoint endpoint;
            BEncodedString failureReasonKey = new BEncodedString("failure reason");
            BEncodedString intervalKey = new BEncodedString("interval");
            BEncodedString completeKey = new BEncodedString("complete");
            BEncodedString incompleteKey = new BEncodedString("incomplete");
            BEncodedString peersKey = new BEncodedString("peers");
            BEncodedString peerIdKey = new BEncodedString("peer id");
            BEncodedString ipaddressKey = new BEncodedString("ip");
            BEncodedString portKey = new BEncodedString("port");

            message = null;

            if (data.IsNotNullOrEmpty())
            {
                value = BEncodedValue.Decode(data);

                if (value is BEncodedDictionary)
                {
                    if (value.As<BEncodedDictionary>().ContainsKey(failureReasonKey) &&
                        value.As<BEncodedDictionary>()[failureReasonKey] is BEncodedString)
                    {
                        faliureReason = value.As<BEncodedDictionary>()[failureReasonKey].As<BEncodedString>().Text;
                    }

                    if (value.As<BEncodedDictionary>().ContainsKey(intervalKey) &&
                        value.As<BEncodedDictionary>()[intervalKey] is BEncodedNumber)
                    {
                        interval = TimeSpan.FromSeconds(value.As<BEncodedDictionary>()[intervalKey].As<BEncodedNumber>().Number);
                    }
                    else
                    {
                        return false;
                    }

                    if (value.As<BEncodedDictionary>().ContainsKey(completeKey) &&
                        value.As<BEncodedDictionary>()[completeKey] is BEncodedNumber)
                    {
                        complete = (int)value.As<BEncodedDictionary>()[completeKey].As<BEncodedNumber>().Number;
                    }
                    else
                    {
                        return false;
                    }

                    if (value.As<BEncodedDictionary>().ContainsKey(incompleteKey) &&
                        value.As<BEncodedDictionary>()[incompleteKey] is BEncodedNumber)
                    {
                        incomplete = (int)value.As<BEncodedDictionary>()[incompleteKey].As<BEncodedNumber>().Number;
                    }
                    else
                    {
                        return false;
                    }

                    if (value.As<BEncodedDictionary>().ContainsKey(peersKey) &&
                        value.As<BEncodedDictionary>()[peersKey] is BEncodedList)
                    {
                        foreach (var item in value.As<BEncodedDictionary>()[peersKey].As<BEncodedList>())
                        {
                            if (item is BEncodedDictionary)
                            {
                                if (item.As<BEncodedDictionary>().ContainsKey(peerIdKey) &&
                                    item.As<BEncodedDictionary>()[peerIdKey] is BEncodedString &&
                                    item.As<BEncodedDictionary>().ContainsKey(ipaddressKey) &&
                                    item.As<BEncodedDictionary>()[ipaddressKey] is BEncodedString &&
                                    item.As<BEncodedDictionary>().ContainsKey(portKey) &&
                                    item.As<BEncodedDictionary>()[portKey] is BEncodedNumber)
                                {
                                    peerId = Message.ToPeerId(Encoding.ASCII.GetBytes(item.As<BEncodedDictionary>()[peerIdKey].As<BEncodedString>().Text));
                                    peerIp = item.As<BEncodedDictionary>()[ipaddressKey].As<BEncodedString>().Text;
                                    peerPort = (int)item.As<BEncodedDictionary>()[portKey].As<BEncodedNumber>().Number;

                                    if (IPAddress.TryParse(peerIp, out tmpIpAddress) &&
                                        peerPort >= IPEndPoint.MinPort &&
                                        peerPort <= IPEndPoint.MaxPort)
                                    {
                                        endpoint = new IPEndPoint(tmpIpAddress, (ushort)peerPort);

                                        if (!peers.ContainsKey(endpoint.ToString()))
                                        {
                                            peers.Add(endpoint.ToString(), endpoint);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                var data2 = item.Encode();

                                for (int i = 0; i < data2.Length; i += 6)
                                {
                                    endpoint = new IPEndPoint(new IPAddress(IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data2, i))), IPAddress.NetworkToHostOrder(BitConverter.ToInt16(data2, i + 4)));

                                    if (!peers.ContainsKey(endpoint.ToString()))
                                    {
                                        peers.Add(endpoint.ToString(), endpoint);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        return false;
                    }
                }

                message = new AnnounceResponseMessage(faliureReason, interval, complete, incomplete, peers.Values);

                return true;
            }

            return false;
        }

19 View Source File : GuidUtils.cs
License : Apache License 2.0
Project Creator : AmpScm

public static Guid CreateGuid(Guid baseUuid, byte[] hashData)
        {
            if (baseUuid == Guid.Empty)
                throw new ArgumentNullException("baseUuid");
            else if (hashData == null)
                throw new ArgumentNullException("hashData");

            // See RFC 4122 for C implementation examples

            byte[] hash;
            using (SHA1 sha1 = SHA1.Create())
            {
                sha1.TransformBlock(GuidToNetworkOrder(baseUuid.ToByteArray()), 0, 16, null, 0);
                sha1.TransformFinalBlock(hashData, 0, hashData.Length);

                hash = sha1.Hash;
            }

            hash = ToHostOrder(hash); // Treat as guid

            Int32 timeLow = BitConverter.ToInt32(hash, 0);
            Int16 timeMid = BitConverter.ToInt16(hash, 4);
            Int16 timeHiAndVersion = BitConverter.ToInt16(hash, 6);
            Byte clockSeqHi = hash[8];
            Byte clockSeqLow = hash[9];

            return new Guid(
                timeLow,
                timeMid,
                (short)((timeHiAndVersion & 0xFFF) | (5 << 12)),
                (byte)((clockSeqHi & 0x3F) | 0x80),
                clockSeqLow,
                hash[10],
                hash[11],
                hash[12],
                hash[13],
                hash[14],
                hash[15]);
        }

19 View Source File : DataBuffer.cs
License : MIT License
Project Creator : AndreasAmMueller

public short GetInt16(int index)
		{
			byte[] blob = GetBytes(index, 2);
			InternalSwap(blob);
			return BitConverter.ToInt16(blob, 0);
		}

19 View Source File : Extensions.cs
License : MIT License
Project Creator : AndreasAmMueller

public static short GetInt16(this ModbusObject register)
		{
			if (register == null)
				throw new ArgumentNullException(nameof(register));

			if (register.Type != ModbusObjectType.HoldingRegister && register.Type != ModbusObjectType.InputRegister)
				throw new ArgumentException("Invalid register type");

			byte[] blob = new[] { register.HiByte, register.LoByte };
			if (BitConverter.IsLittleEndian)
				Array.Reverse(blob);

			return BitConverter.ToInt16(blob, 0);
		}

19 View Source File : MemoryStreamWrapper.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public short ReadInt16(int offset)
        {
            var buffer = ReadStreamAt(offset, Constant.SHORT_BYTES);
            return BitConverter.ToInt16(buffer, 0);
        }

19 View Source File : MemoryStreamWrapper.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

public short ReadInt16()
        {
            byte[] buffer = new byte[Constant.SHORT_BYTES];
            lock (stream)
            {
                stream.Read(buffer, 0, Constant.SHORT_BYTES);
            }          
            return BitConverter.ToInt16(buffer, 0);
        }

19 View Source File : GridBasedStructureDicomLoader.cs
License : Apache License 2.0
Project Creator : 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 View Source File : StreamUtils.cs
License : MIT License
Project Creator : ansel86castro

public static short ReadInt16(Stream stream)
        {
            byte[] buff = new byte[2];

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

19 View Source File : Mappings.cs
License : Apache License 2.0
Project Creator : 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 View Source File : Constant.cs
License : GNU General Public License v3.0
Project Creator : 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 View Source File : EncryptionInfo.cs
License : Apache License 2.0
Project Creator : Appdynamics

internal static EncryptionInfo ReadBinary(byte[] data)
        {
            var majorVersion = BitConverter.ToInt16(data, 0);
            var minorVersion = BitConverter.ToInt16(data, 2);
            EncryptionInfo ret;
            if ((minorVersion == 2 || minorVersion == 3) && majorVersion <= 4) // minorVersion==1 is RC4, not supported.
            {
                ret = new EncryptionInfoBinary();
            }
            else if (majorVersion == 4 && minorVersion==4)
            {
                ret = new EncryptionInfoAgile();
            }
            else
            {
                throw (new NotSupportedException("Unsupported encryption format"));
            }
            ret.MajorVersion = majorVersion;
            ret.MinorVersion = minorVersion;
            ret.Read(data);
            return ret;
        }

19 View Source File : Beacon.cs
License : MIT License
Project Creator : Apr4h

private static int GetConfigFieldDataLength(byte[] configField)
        {
            // Swap endiannes for BitConverter
            byte[] tmp = new byte[2] { configField[3], configField[2] };
            short lengthField = BitConverter.ToInt16(tmp, 0);

            switch (lengthField)
            {
                case 1:
                    return 2;
                case 2:
                    return 4;
                case 3:
                    short length = BitConverter.ToInt16(configField, 4);
                    length = IPAddress.HostToNetworkOrder(length);
                    return (int)length;
                default:
                    return 4;
                    //throw new ArgumentException("Invalid length byte in config field");
            }
        }

19 View Source File : BeaconSetting.cs
License : MIT License
Project Creator : Apr4h

private static int BigEndianBytesToInt(byte[] bytes)
        {
            int number;

            if (bytes.Length == 2)
            {
                number= BitConverter.ToInt16(bytes, 0);
                number = IPAddress.HostToNetworkOrder(number);
            }
            else if (bytes.Length == 4)
            {
                number = BitConverter.ToInt32(bytes, 0);
                number = IPAddress.HostToNetworkOrder(number); 
            }
            else
            {
                throw new System.ArgumentException("'bytes' param should be 2 or 4 bytes in length");
            }

            return number;
        }

19 View Source File : BeaconSetting.cs
License : MIT License
Project Creator : Apr4h

private static short BigEndianBytesToShort(byte[] bytes)
        {
            short number = BitConverter.ToInt16(bytes, 0);
            return IPAddress.HostToNetworkOrder(number);
        }

19 View Source File : RemoteInput.cs
License : Apache License 2.0
Project Creator : araobp

public void ProcessInput(byte[] bytes)
        {
            switch ((EventType)bytes[0])
            {
                case EventType.Keyboard:
                    var type = (KeyboardEventType)bytes[1];
                    var repeat = bytes[2] == 1;
                    var key = bytes[3];
                    var character = (char)bytes[4];
                    ProcessKeyEvent(type, repeat, key, character);
                    break;
                case EventType.Mouse:
                    var deltaX = BitConverter.ToInt16(bytes, 1);
                    var deltaY = BitConverter.ToInt16(bytes, 3);
                    var button = bytes[5];
                    ProcessMouseMoveEvent(deltaX, deltaY, button);
                    break;
                case EventType.MouseWheel:
                    var scrollX = BitConverter.ToSingle(bytes, 1);
                    var scrollY = BitConverter.ToSingle(bytes, 5);
                    ProcessMouseWheelEvent(scrollX, scrollY);
                    break;
                case EventType.Touch:
                    {
                        var length = bytes[1];
                        var index = 2;
                        var touches = new TouchState[length];
                        for (int i = 0; i < length; i++)
                        {
                            const int INPUTSYSTEM_ZERO_ID_GUARD = 128; //ID 0 is reserved by inputsystem
                            int identifier = BitConverter.ToInt32(bytes, index) + INPUTSYSTEM_ZERO_ID_GUARD;
                            index += 4;
                            var phase = (UnityEngine.InputSystem.TouchPhase)bytes[index];
                            index += 1;
                            var pageX = BitConverter.ToInt16(bytes, index);
                            index += 2;
                            var pageY = BitConverter.ToInt16(bytes, index);
                            index += 2;
                            var force = BitConverter.ToSingle(bytes, index);
                            index += 4;
                            touches[i] = new TouchState
                            {
                                touchId = identifier,
                                phase = phase,
                                position = new UnityEngine.Vector2Int(pageX, pageY),
                                pressure = force
                            };
                        }
                        ProcessTouchMoveEvent(touches);
                        if (Touch.activeTouches.Count > length)
                        {
                            ChangeEndStateUnusedTouches(touches);
                        }
                    }
                    
                    break;
                case EventType.ButtonClick:
                    var elementId = BitConverter.ToInt16(bytes, 1);
                    ProcessButtonClickEvent(elementId);
                    break;
                case EventType.Gamepad:
                    {
                        GamepadEventType gamepadEventType = (GamepadEventType)bytes[1];
                        
                        switch (gamepadEventType)
                        {
                            case GamepadEventType.ButtonDown:
                            case GamepadEventType.ButtonUp:
                            case GamepadEventType.ButtonPressed:
                                {
                                    var buttonIndex = bytes[2];
                                    var value = BitConverter.ToDouble(bytes, 3);
                                    ProcessGamepadButtonEvent(gamepadEventType, (GamepadKeyCode) buttonIndex, value);
                                }
                                break;
                            case GamepadEventType.Axis:
                                {
                                    var buttonIndex = bytes[2];
                                    var x = BitConverter.ToDouble(bytes, 3);
                                    var y = BitConverter.ToDouble(bytes, 11);
                                    ProcessGamepadAxisEvent(x, y, (GamepadKeyCode) buttonIndex);
                                }
                                break;
                        }
                        InputSystem.QueueStateEvent(RemoteGamepad, m_gamepadState);
                    }
                    break;
            }
        }

19 View Source File : Endian.cs
License : MIT License
Project Creator : Arefu

public static short ToInt16(byte[] value, int startIndex, bool convert)
        {
            var result = BitConverter.ToInt16(value, startIndex);
            return convert ? ConvertInt16(result) : result;
        }

19 View Source File : BookRequestSerializer.cs
License : MIT License
Project Creator : ArjunVachhani

[SuppressMessage("Microsoft.Globalization", "CA1303")]
        public static BookRequest Deserialize(ReadOnlySpan<byte> bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes));

            if (bytes.Length != sizeOfMessage)
                throw new Exception("Book Request Message must be of Size : " + sizeOfMessage);

            var messageType = (MessageType)(bytes[messageTypeOffset]);

            if (messageType != MessageType.BookRequest)
                throw new Exception(Constant.INVALID_MESSAGE);

            var version = BitConverter.ToInt16(bytes.Slice(versionOffset));

            if (version != BookRequestSerializer.version)
                throw new Exception(Constant.INVALID_VERSION);

            var bookRequest = new BookRequest();

            bookRequest.LevelCount = BitConverter.ToInt32(bytes.Slice(levelCountOffset));

            return bookRequest;
        }

19 View Source File : BookSerializer.cs
License : MIT License
Project Creator : ArjunVachhani

[SuppressMessage("Microsoft.Globalization", "CA1303")]
        public static BookDepth Deserialize(ReadOnlySpan<byte> bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes));

            if (bytes.Length < minMessageSize)
                throw new Exception("Book Message must be greater than of Size : " + minMessageSize);

            var messageType = (MessageType)(bytes[messageTypeOffset]);
            if (messageType != MessageType.Book)
            {
                throw new Exception(Constant.INVALID_MESSAGE);
            }

            var version = BitConverter.ToInt16(bytes.Slice(versionOffset));
            if (version != BookSerializer.version)
            {
                throw new Exception(Constant.INVALID_VERSION);
            }

            var timeStamp = BitConverter.ToInt32(bytes.Slice(timeStampOffset));
            Price? ltp = ReadPrice(bytes.Slice(ltpOffset));
            if (ltp == 0)
            {
                ltp = null;
            }


            var bidCount = BitConverter.ToInt16(bytes.Slice(bidCountOffset));
            var askCount = BitConverter.ToInt16(bytes.Slice(askCountOffset));

            List<KeyValuePair<Price, Quanreplacedy>> bid = new List<KeyValuePair<Price, Quanreplacedy>>(bidCount);
            List<KeyValuePair<Price, Quanreplacedy>> ask = new List<KeyValuePair<Price, Quanreplacedy>>(askCount);
            for (int i = 0; i < bidCount; i++)
            {
                var price = ReadPrice(bytes.Slice(bidStartOffset + (i * sizeOfLevel)));
                var quanreplacedy = ReadQuanreplacedy(bytes.Slice(bidStartOffset + (i * sizeOfLevel) + sizeOfPrice));
                bid.Add(new KeyValuePair<Price, Quanreplacedy>(price, quanreplacedy));
            }
            var askStartOffset = bidStartOffset + (bidCount * sizeOfLevel);
            for (int i = 0; i < askCount; i++)
            {
                var price = ReadPrice(bytes.Slice(askStartOffset + (i * sizeOfLevel)));
                var quanreplacedy = ReadQuanreplacedy(bytes.Slice(askStartOffset + (i * sizeOfLevel) + sizeOfPrice));
                ask.Add(new KeyValuePair<Price, Quanreplacedy>(price, quanreplacedy));
            }

            var book = new BookDepth(timeStamp, ltp, bid,ask);
            return book;
        }

19 View Source File : CancelledOrderSerializer.cs
License : MIT License
Project Creator : ArjunVachhani

[SuppressMessage("Microsoft.Globalization", "CA1303")]
        public static CancelledOrder Deserialize(ReadOnlySpan<byte> bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes));

            if (bytes.Length != sizeOfMessage)
                throw new Exception("Canceled Order Message must be of Size : " + sizeOfMessage);

            var messageType = (MessageType)(bytes[messageTypeOffset]);

            if (messageType != MessageType.Cancel)
                throw new Exception(Constant.INVALID_MESSAGE);

            var version = BitConverter.ToInt16(bytes.Slice(versionOffset));

            if (version != CancelledOrderSerializer.version)
                throw new Exception(Constant.INVALID_VERSION);

            var cancelledOrder = new CancelledOrder();

            cancelledOrder.OrderId = BitConverter.ToInt32(bytes.Slice(orderIdOffset));
            cancelledOrder.RemainingQuanreplacedy = ReadQuanreplacedy(bytes.Slice(remainingQuanreplacedyOffset));
            cancelledOrder.CancelReason = (CancelReason)bytes[cancelReasonOffset];
            cancelledOrder.Timestamp = BitConverter.ToInt32(bytes.Slice(timestampOffset));
            cancelledOrder.Cost = ReadQuanreplacedy(bytes.Slice(costOffset));
            cancelledOrder.Fee = ReadQuanreplacedy(bytes.Slice(feeOffset));
            cancelledOrder.MessageSequence = BitConverter.ToInt64(bytes.Slice(messageSequenceOffset));

            return cancelledOrder;
        }

19 View Source File : CancelRequestSerializer.cs
License : MIT License
Project Creator : ArjunVachhani

[SuppressMessage("Microsoft.Globalization", "CA1303")]
        public static CancelRequest Deserialize(ReadOnlySpan<byte> bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes));

            if (bytes.Length != sizeOfMessage)
                throw new Exception("Cancel Request Message must be of Size : " + sizeOfMessage);

            var messageType = (MessageType)(bytes[messageTypeOffset]);

            if (messageType != MessageType.CancelRequest)
                throw new Exception(Constant.INVALID_MESSAGE);

            var version = BitConverter.ToInt16(bytes.Slice(versionOffset));

            if (version != CancelRequestSerializer.version)
                throw new Exception(Constant.INVALID_VERSION);

            var cancelRequest = new CancelRequest();

            cancelRequest.OrderId = BitConverter.ToInt32(bytes.Slice(orderIdOffset));

            return cancelRequest;
        }

19 View Source File : FillSerializer.cs
License : MIT License
Project Creator : ArjunVachhani

[SuppressMessage("Microsoft.Globalization", "CA1303")]
        public static Fill Deserialize(ReadOnlySpan<byte> bytes)
        {
            if (bytes == null)
                throw new ArgumentNullException(nameof(bytes));

            if (bytes.Length != sizeOfMessage)
                throw new Exception("Fill Message must be of Size : " + sizeOfMessage);

            var messageType = (MessageType)(bytes[messageTypeOffset]);

            if (messageType != MessageType.Fill)
                throw new Exception(Constant.INVALID_MESSAGE);

            var version = BitConverter.ToInt16(bytes.Slice(versionOffset));

            if (version != FillSerializer.version)
                throw new Exception(Constant.INVALID_VERSION);

            var fill = new Fill();
            fill.MakerOrderId = BitConverter.ToInt32(bytes.Slice(makerOrderIdOffset));
            fill.TakerOrderId = BitConverter.ToInt32(bytes.Slice(takerOrderIdOffset));
            fill.MatchRate = ReadPrice(bytes.Slice(matchRateOffset));
            fill.MatchQuanreplacedy = ReadQuanreplacedy(bytes.Slice(matchQuanreplacedyOffset));
            fill.Timestamp = BitConverter.ToInt32(bytes.Slice(timestampOffset));
            fill.MessageSequence = BitConverter.ToInt64(bytes.Slice(messageSequenceOffset));

            if (Convert.ToBoolean(bytes[isAskRemainingNullOffset]))
                fill.AskRemainingQuanreplacedy = ReadQuanreplacedy(bytes.Slice(askRemainingQuanreplacedyOffset));

            if (Convert.ToBoolean(bytes[isAskFeeNullOffset]))
                fill.AskFee = ReadQuanreplacedy(bytes.Slice(askFeeOffset));

            if (Convert.ToBoolean(bytes[isBidCostNullOffset]))
                fill.BidCost = ReadQuanreplacedy(bytes.Slice(bidCostOffset));

            if (Convert.ToBoolean(bytes[isBidFeeNullOffset]))
                fill.BidFee = ReadQuanreplacedy(bytes.Slice(bidFeeOffset));

            return fill;
        }

See More Examples