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

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

693 Examples 7

19 View Source File : Protocol16Deserializer.cs
License : MIT License
Project Creator : 0blu

private static float DeserializeFloat(Protocol16Stream input)
        {
            var buffer = _byteBuffer.Value;
            input.Read(buffer, 0, sizeof(float));

            if (BitConverter.IsLittleEndian)
            {
                byte b0 = buffer[0];
                byte b1 = buffer[1];
                buffer[0] = buffer[3];
                buffer[1] = buffer[2];
                buffer[2] = b1;
                buffer[3] = b0;
            }

            return BitConverter.ToSingle(buffer, 0);
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : NetworkUtils.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static Vector2 DeserializeVector2(byte[] data, ref int offset)
    {
        Vector2 ret = Vector2.zero;
        ret.x = BitConverter.ToSingle(data, offset);
        offset += sizeof(float);
        ret.y = BitConverter.ToSingle(data, offset);
        offset += sizeof(float);
        return ret;
    }

19 View Source File : NetworkUtils.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static Vector3 DeserializeVector3(byte[] data, ref int offset)
    {
        Vector3 ret = Vector3.zero;
        ret.x = BitConverter.ToSingle(data, offset);
        offset += sizeof(float);
        ret.y = BitConverter.ToSingle(data, offset);
        offset += sizeof(float);
        ret.z = BitConverter.ToSingle(data, offset);
        offset += sizeof(float);
        return ret;
    }

19 View Source File : NetworkUtils.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static float DeserializeFloat(byte[] data, ref int offset)
    {
        float ret = BitConverter.ToSingle(data, offset);
        offset += sizeof(float);
        return ret;
    }

19 View Source File : PlyHandler.cs
License : MIT License
Project Creator : 3DBear

private static List<Vector3> GetVertices(byte[] bytes, PlyHeader header, out List<Color> colors)
        {
            var vertices = new List<Vector3>();
            colors = new List<Color>();
            int bpvc = 4; // bytes per vertex component
            int bpcc = 1; // bytes per color component
            bool hasColor = header.RedIndex.HasValue && header.GreenIndex.HasValue && header.BlueIndex.HasValue;
            // todo: support other types than just float for vertex components and byte for color components
            int bytesPerVertex = GetByteCountPerVertex(header);

            for (int i = 0; i < header.VertexCount; i++)
            {
                int byteIndex = i * bytesPerVertex;
                var x = System.BitConverter.ToSingle(bytes.SubArray(byteIndex + 0 * bpvc, bpvc), 0);
                var y = System.BitConverter.ToSingle(bytes.SubArray(byteIndex + 1 * bpvc, bpvc), 0);
                var z = System.BitConverter.ToSingle(bytes.SubArray(byteIndex + 2 * bpvc, bpvc), 0);
                if (hasColor)
                {
                    byte r, g, b, a = 255;
                    r = bytes[byteIndex + 3 * bpvc + 0 * bpcc];
                    g = bytes[byteIndex + 3 * bpvc + 1 * bpcc];
                    b = bytes[byteIndex + 3 * bpvc + 2 * bpcc];
                    if (header.AlphaIndex.HasValue)
                    {
                        a = bytes[byteIndex + 3 * bpvc + 3 * bpcc];
                    }
                    colors.Add(new Color(r/255f, g/255f, b/255f, a/255f));
                }


                vertices.Add(new Vector3(x, y, z));
            }
            return vertices;
        }

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 : CodedInputStream.cs
License : MIT License
Project Creator : 404Lcc

public float ReadFloat()
        {
            if (BitConverter.IsLittleEndian && 4 <= bufferSize - bufferPos)
            {
                float ret = BitConverter.ToSingle(buffer, bufferPos);
                bufferPos += 4;
                return ret;
            }
            else
            {
                byte[] rawBytes = ReadRawBytes(4);
                if (!BitConverter.IsLittleEndian)
                {
                    ByteArray.Reverse(rawBytes);
                }
                return BitConverter.ToSingle(rawBytes, 0);
            }
        }

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

public float bytesToFloat (byte[] inputBytes)
		{
			float result = 0;
			if (a_Stream.endian == EndianType.BigEndian) { Array.Reverse(inputBytes); }

			switch (inputBytes.Length)
			{
				case 1:
					result = inputBytes[0] / 255.0f;
					break;
				case 2:
					result = Half.ToHalf(inputBytes, 0);
					break;
				case 4:
					result = BitConverter.ToSingle(inputBytes, 0);
					break;
			}

			return result;
		}

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

public override float ReadSingle()
        {
            if (endian == EndianType.BigEndian)
            {
                a32 = ReadBytes(4);
                Array.Reverse(a32);
                return BitConverter.ToSingle(a32, 0);
            }
            return base.ReadSingle();
        }

19 View Source File : MessageDecoder.cs
License : MIT License
Project Creator : Abaudat

static Vector3 ByteArrayToVector3(byte[] data)
    {
        byte[] buff = data;
        Vector3 vect = Vector3.zero;
        vect.x = BitConverter.ToSingle(buff, 0 * sizeof(float));
        vect.y = BitConverter.ToSingle(buff, 1 * sizeof(float));
        vect.z = BitConverter.ToSingle(buff, 2 * sizeof(float));
        return vect;
    }

19 View Source File : GltfConversions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

internal static Vector4[] GetVector4Array(this GltfAccessor accessor, bool convert = true)
        {
            if (accessor.type != vec4 || accessor.componentType == GltfComponentType.UnsignedInt)
            {
                return null;
            }

            var array = new Vector4[accessor.count];

            GetTypeDetails(accessor.componentType, out int componentSize, out float maxValue);
            var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize * 4;
            var byteOffset = accessor.BufferView.byteOffset;
            var bufferData = accessor.BufferView.Buffer.BufferData;

            if (accessor.byteOffset >= 0)
            {
                byteOffset += accessor.byteOffset;
            }

            if (accessor.normalized) { maxValue = 1; }

            for (int i = 0; i < accessor.count; i++)
            {
                if (accessor.componentType == GltfComponentType.Float)
                {
                    array[i].x = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 0);
                    array[i].y = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 1);
                    array[i].z = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 2);
                    array[i].w = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 3);
                }
                else
                {
                    array[i].x = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 0, accessor.componentType) / maxValue;
                    array[i].y = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 1, accessor.componentType) / maxValue;
                    array[i].z = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 2, accessor.componentType) / maxValue;
                    array[i].w = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 3, accessor.componentType) / maxValue;
                }

                if (convert)
                {
                    array[i].x *= TangentSpaceConversionScale.x;
                    array[i].y *= TangentSpaceConversionScale.y;
                    array[i].z *= TangentSpaceConversionScale.z;
                    array[i].w *= TangentSpaceConversionScale.w;
                }
            }

            return array;
        }

19 View Source File : GltfConversions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

internal static Color[] GetColorArray(this GltfAccessor accessor)
        {
            if (accessor.type != vec3 && accessor.type != vec4 || accessor.componentType == GltfComponentType.UnsignedInt)
            {
                return null;
            }

            var array = new Color[accessor.count];

            GetTypeDetails(accessor.componentType, out int componentSize, out float maxValue);
            bool hasAlpha = accessor.type == vec4;

            var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize * (hasAlpha ? 4 : 3);
            var byteOffset = accessor.BufferView.byteOffset;
            var bufferData = accessor.BufferView.Buffer.BufferData;

            if (accessor.byteOffset >= 0)
            {
                byteOffset += accessor.byteOffset;
            }

            for (int i = 0; i < accessor.count; i++)
            {
                if (accessor.componentType == GltfComponentType.Float)
                {
                    array[i].r = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 0);
                    array[i].g = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 1);
                    array[i].b = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 2);
                    array[i].a = hasAlpha ? BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 3) : 1f;
                }
                else
                {
                    array[i].r = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 0, accessor.componentType) / maxValue;
                    array[i].g = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 1, accessor.componentType) / maxValue;
                    array[i].b = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 2, accessor.componentType) / maxValue;
                    array[i].a = hasAlpha ? GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 3, accessor.componentType) / maxValue : 1f;
                }
            }

            return array;
        }

19 View Source File : GltfConversions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

internal static Vector2[] GetVector2Array(this GltfAccessor accessor, bool flip = true)
        {
            if (accessor.type != vec2 || accessor.componentType == GltfComponentType.UnsignedInt)
            {
                return null;
            }

            var array = new Vector2[accessor.count];

            GetTypeDetails(accessor.componentType, out int componentSize, out float maxValue);
            var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize * 2;
            var byteOffset = accessor.BufferView.byteOffset;
            var bufferData = accessor.BufferView.Buffer.BufferData;

            if (accessor.byteOffset >= 0)
            {
                byteOffset += accessor.byteOffset;
            }

            if (accessor.normalized) { maxValue = 1; }

            for (int i = 0; i < accessor.count; i++)
            {
                if (accessor.componentType == GltfComponentType.Float)
                {
                    array[i].x = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 0);
                    array[i].y = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 1);
                }
                else
                {
                    array[i].x = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 0, accessor.componentType) / maxValue;
                    array[i].y = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 1, accessor.componentType) / maxValue;
                }

                if (flip)
                {
                    array[i].y = 1.0f - array[i].y;
                }
            }

            return array;
        }

19 View Source File : GltfConversions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

internal static int[] GetIntArray(this GltfAccessor accessor, bool flipFaces = true)
        {
            if (accessor.type != scalar)
            {
                return null;
            }

            var array = new int[accessor.count];

            GetTypeDetails(accessor.componentType, out int componentSize, out float _);
            var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize;
            var byteOffset = accessor.BufferView.byteOffset;
            var bufferData = accessor.BufferView.Buffer.BufferData;

            if (accessor.byteOffset >= 0)
            {
                byteOffset += accessor.byteOffset;
            }

            for (int i = 0; i < accessor.count; i++)
            {
                if (accessor.componentType == GltfComponentType.Float)
                {
                    array[i] = (int)Mathf.Floor(BitConverter.ToSingle(bufferData, byteOffset + i * stride));
                }
                else
                {
                    array[i] = (int)GetDiscreteUnsignedElement(bufferData, byteOffset + i * stride, accessor.componentType);
                }
            }

            if (flipFaces)
            {
                for (int i = 0; i < array.Length; i += 3)
                {
                    var temp = array[i];
                    array[i] = array[i + 2];
                    array[i + 2] = temp;
                }
            }

            return array;
        }

19 View Source File : GltfConversions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

internal static Vector3[] GetVector3Array(this GltfAccessor accessor, bool convert = true)
        {
            if (accessor.type != vec3 || accessor.componentType == GltfComponentType.UnsignedInt)
            {
                return null;
            }

            var array = new Vector3[accessor.count];

            GetTypeDetails(accessor.componentType, out int componentSize, out float maxValue);
            var stride = accessor.BufferView.byteStride > 0 ? accessor.BufferView.byteStride : componentSize * 3;
            var byteOffset = accessor.BufferView.byteOffset;
            var bufferData = accessor.BufferView.Buffer.BufferData;

            if (accessor.byteOffset >= 0)
            {
                byteOffset += accessor.byteOffset;
            }

            if (accessor.normalized) { maxValue = 1; }

            for (int i = 0; i < accessor.count; i++)
            {
                if (accessor.componentType == GltfComponentType.Float)
                {
                    array[i].x = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 0);
                    array[i].y = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 1);
                    array[i].z = BitConverter.ToSingle(bufferData, byteOffset + i * stride + componentSize * 2);
                }
                else
                {
                    array[i].x = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 0, accessor.componentType) / maxValue;
                    array[i].y = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 1, accessor.componentType) / maxValue;
                    array[i].z = GetDiscreteElement(bufferData, byteOffset + i * stride + componentSize * 2, accessor.componentType) / maxValue;
                }

                if (convert)
                {
                    array[i].x *= CoordinateSpaceConversionScale.x;
                    array[i].y *= CoordinateSpaceConversionScale.y;
                    array[i].z *= CoordinateSpaceConversionScale.z;
                }
            }

            return array;
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

float ReadFloat(byte[] buf, ref int offset)
    {
        float val = BitConverter.ToSingle(buf, offset);
        offset += sizeof(float);
        return val;
    }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

float UnpackFloat(byte[] buf, ref int offset)
		{
			float value = BitConverter.ToSingle(buf, offset);
			offset += 4;
			return value;
		}

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

public void GetRemoteHeadTransform(Transform headTransform)
		{
			bool hasNewTransform = false;

			Packet packet;
			while ((packet = Net.ReadPacket()) != null)
			{
				if (packet.Size != PACKET_SIZE)
				{
					Debug.Log("Invalid packet size: " + packet.Size);
					continue;
				}

				packet.ReadBytes(receiveTransformBuffer);

				if (receiveTransformBuffer[0] != PACKET_FORMAT)
				{
					Debug.Log("Invalid packet type: " + packet.Size);
					continue;
				}
				hasNewTransform = true;
			}

			if (hasNewTransform)
			{
				receivedPositionPrior = receivedPosition;
				receivedPosition.x = BitConverter.ToSingle(receiveTransformBuffer, 1);
				receivedPosition.y = BitConverter.ToSingle(receiveTransformBuffer, 5);
				receivedPosition.z = BitConverter.ToSingle(receiveTransformBuffer, 9);

				receivedRotationPrior = receivedRotation;
				receivedRotation.x = BitConverter.ToSingle(receiveTransformBuffer, 13);
				receivedRotation.y = BitConverter.ToSingle(receiveTransformBuffer, 17) * -1.0f;
				receivedRotation.z = BitConverter.ToSingle(receiveTransformBuffer, 21);
				receivedRotation.w = BitConverter.ToSingle(receiveTransformBuffer, 25) * -1.0f;

				receivedTime = Time.time;
			}

			// since we're receiving updates at a slower rate than we render,
			// interpolate to make the motion look smoother
			float completed = Math.Min(Time.time - receivedTime, UPDATE_DELAY) / UPDATE_DELAY;
			headTransform.localPosition =
				Vector3.Lerp(receivedPositionPrior, receivedPosition, completed);
			headTransform.localRotation =
				Quaternion.Slerp(receivedRotationPrior, receivedRotation, completed);
		}

19 View Source File : SampleReader.cs
License : MIT License
Project Creator : ABTSoftware

private double ReadSample(byte[] data, int idx)
        {
            double result = 0;
            var pos = idx * _bytesPerFrame;
            for (int i = 0; i < _channels; i++)
            {
                var val = BitConverter.ToSingle(data, pos + _bytesPerSample * i);
                result += val;
            }
            result /= _channels;
            return result;
        }

19 View Source File : CommandInterpreter.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public void HandleKeyboardCommand(CmdStruct cmdStruct, MotionCommand command)
        {
            // vfptr[12] - IsActive
            if (!IsActive()) return;

            bool start;

            if (cmdStruct.Command == MotionCommand.AutoRun)
            {
                start = Convert.ToBoolean(cmdStruct.Args[cmdStruct.Curr]);
                cmdStruct.Curr++;
                if (cmdStruct.Curr >= cmdStruct.Size)
                {
                    AutoRunSpeed = 1.0f;
                }
                else
                {
                    AutoRunSpeed = BitConverter.ToSingle(BitConverter.GetBytes(cmdStruct.Args[cmdStruct.Curr]));
                    cmdStruct.Curr++;
                }
                // vfptr[16].OnLoseFocus - ToggleAutoRun
                ToggleAutoRun();
                // vfptr[6].OnAction - SendMovementEvent
                SendMovementEvent();
                return;
            }

            if (((uint)cmdStruct.Command & (uint)CommandMask.UI) != 0)
                return;

            start = Convert.ToBoolean(cmdStruct.Args[cmdStruct.Curr]);
            cmdStruct.Curr++;

            var speed = 1.0f;
            if (cmdStruct.Curr < cmdStruct.Size)
            {
                speed = BitConverter.ToSingle(BitConverter.GetBytes(cmdStruct.Args[cmdStruct.Curr]));
                cmdStruct.Curr++;
            }

            if (ControlledByServer && !start)
            {
                // vfptr[1].OnLoseFocus - MovePlayer?
                MovePlayer((MotionCommand)cmdStruct.Command, start, speed, false, false);
                return;
            }

            // vfptr[8].OnLoseFocus(a2) - ACCmdInterp::TakeControlFromServer?
            TakeControlFromServer();

            if (cmdStruct.Command == MotionCommand.HoldRun‬)
            {
                // vfptr[2].OnLoseFocus

                if (!IsStandingStill())
                    SendMovementEvent();

                return;
            }

            if (cmdStruct.Command == MotionCommand.HoldSidestep)
            {
                // vfptr[3]

                if (!IsStandingStill())
                    SendMovementEvent();

                return;
            }

            // vfptr[2] - Bookkeep
            if (!BookkeepCommandAndModifyIfNecessary(cmdStruct.Command, start, speed, false, false))
            {
                SendMovementEvent();
                return;
            }

            // vfptr[4].OnAction - ApplyHoldKeysToCommand
            ApplyHoldKeysToCommand(ref cmdStruct.Command, speed);

            // vfptr[13].OnAction - MovePlayer
            MovePlayer(cmdStruct.Command, start, speed, false, false);

            // vfptr[6].OnAction - SendMovementEvent
            if (cmdStruct.Command != MotionCommand.Jump)
                SendMovementEvent();
        }

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static float GetSingle(byte[] data, int index = 0) 
            => BitConverter.ToSingle(data, index);

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static Point GetPoint(byte[] data, int index = 0)
        {
            //struct of 2 singles (it should be double, but this is a nice bug. Try using double.maxvalue in your uwp code, save it, and then read from it. Infinity.)
            double x = BitConverter.ToSingle(data, index + 0);
            double y = BitConverter.ToSingle(data, index + 4);

            return new Point(x, y);
        }

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static Size GetSize(byte[] data, int index = 0)
        {
            double width = BitConverter.ToSingle(data, index + 0);
            double height = BitConverter.ToSingle(data, index + 4);

            return new Size(width, height);
        }

19 View Source File : Deserializer.cs
License : MIT License
Project Creator : ADeltaX

public static Rect GetRect(byte[] data, int index = 0)
        {
            double x = BitConverter.ToSingle(data, index + 0);
            double y = BitConverter.ToSingle(data, index + 4);
            double width = BitConverter.ToSingle(data, index + 8);
            double height = BitConverter.ToSingle(data, index + 12);

            return new Rect(x, y, width, height);
        }

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

public float ReadFloat() {
			var bytes = ReadBytes(4);
			EndianUtility.EndianCorrection(bytes);
			return BitConverter.ToSingle(bytes, 0);
		}

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

public static float ToFloat(this byte[] bytes) {
            return BitConverter.ToSingle(bytes, 0);
        }

19 View Source File : ConversionTablePlugin.cs
License : GNU General Public License v2.0
Project Creator : afrantzis

void UpdateFloat(DataView dv)
	{
		long offset = dv.CursorOffset;

		// make sure offset is valid for 32 bit float (and 64 bit)
		if (offset < dv.Buffer.Size - 3 && offset >= 0) {
			// create byte[] with float bytes
			byte[] ba = new byte[8];

			// fill byte[] according to endianess
			if (littleEndian)
				for (int i = 0; i < 4; i++)
					ba[i] = dv.Buffer[offset+i];
			else
				for (int i = 0; i < 4; i++)
					ba[3-i] = dv.Buffer[offset+i];

			// set float 32bit
			float f = BitConverter.ToSingle(ba, 0);
			Float32bitEntry.Text = f.ToString();

			// make sure offset is valid for 64 bit float
			if (offset < dv.Buffer.Size - 7) {
				// fill byte[] according to endianess
				if (littleEndian)
					for (int i = 4; i < 8; i++)
						ba[i] = dv.Buffer[offset+i];
				else
					for (int i = 0; i < 8; i++)
						ba[7-i] = dv.Buffer[offset+i];

				// set float 64bit
				double d = BitConverter.ToDouble(ba, 0);
				Float64bitEntry.Text = d.ToString();
			}
			else
				Float64bitEntry.Text = "---";
		}
		else {
			ClearFloat();
		}

	}

19 View Source File : Memory.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

public float ReadFloat(dword_ptr ptr)
        {
            byte[] buffer = new byte[sizeof(float)];
            IntPtr hProc;

            try { hProc = OpenProcess(READ, false, pid); }
            catch (Exception e) { throw new Exception(String.Format("Failed to open the process handle during a ReadFloat statement;\n{0}", e.Message)); }

            if (hProc != IntPtr.Zero)
            {
                try { ReadProcessMemory(hProc, ptr, buffer, sizeof(float), 0); }
                catch (Exception e) { throw new Exception(String.Format("Failed to read process memory during a ReadFloat statement; Address = {0:X}\nWin32 Error: {1}", ptr, e.Message)); }

                CloseHandle(hProc);
            }

            return BitConverter.ToSingle(buffer, 0);
        }

19 View Source File : Memory.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

public float ReadFloat(uint ptr)
        {
            byte[] buffer = new byte[sizeof(float)];
            uint hProc;

            try { hProc = OpenProcess(READ, false, pid); }
            catch (Win32Exception e) { throw new Exception(String.Format("Failed to open the process handle during a ReadFloat statement;\n{0}", e.Message)); }

            if (hProc > 0)
            {
                try { ReadProcessMemory(hProc, ptr, buffer, sizeof(float), 0); }
                catch (Win32Exception e) { throw new Exception(String.Format("Failed to read process memory during a ReadFloat statement; Address = {0:X}\nWin32 Error: {1}", ptr, e.Message)); }

                CloseHandle(hProc);
            }

            return BitConverter.ToSingle(buffer, 0); //* 65.0f;
        }

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 : ProcessExtensions.cs
License : GNU General Public License v3.0
Project Creator : aglab2

public static float ToFloatBits(this uint i)
        {
            return BitConverter.ToSingle(BitConverter.GetBytes(i), 0);
        }

19 View Source File : Memory.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

public float ReadFloat(int ptr)
        {
            byte[] buffer = new byte[sizeof(float)];
            IntPtr hProc;

            try { hProc = OpenProcess(READ, false, pid); }
            catch (Exception e) { throw new Exception(String.Format("Failed to open the process handle during a ReadFloat statement;\n{0}", e.Message)); }

            if (hProc != IntPtr.Zero)
            {
                try { ReadProcessMemory(hProc, ptr, buffer, sizeof(float), 0); }
                catch (Exception e) { throw new Exception(String.Format("Failed to read process memory during a ReadFloat statement; Address = {0:X}\nWin32 Error: {1}", ptr, e.Message)); }

                CloseHandle(hProc);
            }

            return BitConverter.ToSingle(buffer, 0); //* 65.0f;
        }

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

public override float ReadSingle()
        {
            byte[] byteBuffer = BitConverter.GetBytes(ReadUInt32());
            return BitConverter.ToSingle(byteBuffer, 0);
        }

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 : 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 : WebassemblyModule.cs
License : MIT License
Project Creator : alexanderkyte

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		protected float LoadSingle (int offset) {
			return BitConverter.ToSingle (this.Copy (offset, 4), 0);
		}

19 View Source File : ProcessMemory.cs
License : MIT License
Project Creator : altskop

public float CallFunctionFloat(IntPtr functionPtr, IntPtr param)
        {
            float ret = 0;

            byte[] inline = { 0x68,0,0,0,0,0xFF, 0x15, 0, 0, 0, 0, 0xD9, 0x1D, 0, 0, 0, 0, 0xA1, 0, 0, 0, 0,0x59, 0xC3,0,0,0,0,0,0,0,0 };

            IntPtr destination = this.MemAlloc((uint)inline.Length);

            Buffer.BlockCopy(BitConverter.GetBytes((int)param), 0, inline, 1, 4);

            Buffer.BlockCopy(BitConverter.GetBytes((int)functionPtr), 0, inline, 24, 4);
            Buffer.BlockCopy(BitConverter.GetBytes((int)destination + 24), 0, inline, 7, 4);

            byte[] pReturnValue = BitConverter.GetBytes((int)destination + 28);
            Buffer.BlockCopy(pReturnValue, 0, inline, 13, 4);
            Buffer.BlockCopy(pReturnValue, 0, inline, 18, 4);

            this.Write(destination, inline);
            int littleEndian = this.CallFunction(destination, IntPtr.Zero);
            ret = BitConverter.ToSingle(BitConverter.GetBytes(littleEndian).ToArray(), 0);
            bool success = this.MemFree(destination);

            return ret;
        }

19 View Source File : Visualization.cs
License : MIT License
Project Creator : AmigoCap

public override float ReadSingle() {
                var data = base.ReadBytes(4);
                Array.Reverse(data);
                return BitConverter.ToSingle(data, 0);
            }

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

public static float GetSingle(this IEnumerable<ModbusObject> list, int startIndex = 0, bool inverseRegisters = false)
		{
			if (list == null)
				throw new ArgumentNullException(nameof(list));

			int count = list.Count();
			if (count < 2)
				throw new ArgumentException("At least two registers needed", nameof(list));

			if (startIndex < 0 || count < startIndex + 2)
				throw new ArgumentOutOfRangeException(nameof(startIndex));

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

			list = list.OrderBy(r => r.Address).Skip(startIndex).Take(2);
			if (inverseRegisters)
				list = list.Reverse();

			var registers = list.ToArray();
			byte[] blob = new byte[registers.Length * 2];

			for (int i = 0; i < registers.Length; i++)
			{
				blob[i * 2] = registers[i].HiByte;
				blob[i * 2 + 1] = registers[i].LoByte;
			}

			if (BitConverter.IsLittleEndian)
				Array.Reverse(blob);

			return BitConverter.ToSingle(blob, 0);
		}

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

public float GetSingle(int index)
		{
			byte[] blob = GetBytes(index, 4);
			InternalSwap(blob);
			return BitConverter.ToSingle(blob, 0);
		}

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 : MemoryImageStream.cs
License : GNU General Public License v3.0
Project Creator : anydream

public float ReadSingle() {
			if (position + 3 >= dataEnd)
				throw new IOException("Can't read one Single");
			var val = BitConverter.ToSingle(data, position);
			position += 4;
			return val;
		}

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 float ConvertSingle(float value)
        {
            var buffer = BitConverter.GetBytes(value);
            Array.Reverse(buffer);
            return BitConverter.ToSingle(buffer, 0);
        }

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

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

19 View Source File : ArchiveReader.cs
License : MIT License
Project Creator : ark-mod

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void GetFloat(out float value, string varName)
        {
            const int byteSize = 4;
            if ((_size == 0 || _size - _offset < byteSize) && !Prepare(byteSize)) throw new IndexOutOfRangeException();

            _structureLog?.Add<float>(_position, byteSize, varName);

            value = BitConverter.ToSingle(_mem.Span.Slice(_offset));
            _offset += byteSize;
            _position += byteSize;
        }

19 View Source File : Microphone.cs
License : GNU General Public License v3.0
Project Creator : arminkz

void OnDataAvailable(object sender, WaveInEventArgs e)
        {
            byte[] buffer = e.Buffer;
            int bytesRecorded = e.BytesRecorded;
            int bufferIncrement = waveIn.WaveFormat.BlockAlign;

            for (int index = 0; index < bytesRecorded; index += bufferIncrement)
            {
                float sample32 = BitConverter.ToSingle(buffer, index);
                sampleAggregator.Add(sample32);
                //Console.Write("A");
            }
            /*if (this.InvokeRequired)
            {
                this.BeginInvoke(new EventHandler<WaveInEventArgs>(OnDataAvailable), sender, e);
            }
            else
            {

            }*/
        }

19 View Source File : AccurateBinaryReader.cs
License : GNU General Public License v3.0
Project Creator : Artentus

public override float ReadSingle() => BitConverter.ToSingle(ReadRaw(sizeof(float)), 0);

See More Examples