System.BitConverter.GetBytes(bool)

Here are the examples of the csharp api System.BitConverter.GetBytes(bool) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

81 Examples 7

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

public static void SerializeBool(List<byte> byteList, bool data)
    {
        byteList.AddRange(BitConverter.GetBytes(data));
    }

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

public static byte[] FromBoolean(bool data, DateTimeOffset? timestamp = null)
            => BitConverter.GetBytes(data).AppendTimestamp(timestamp);

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

public static byte[] GetBytes(this bool value) {
            return BitConverter.GetBytes(value);
        }

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

[Fact]
        public void WriteboolMinTest()
        {
            var arr1 = new byte[1];
            Serializer.Write(arr1, true);
            var arr2 = BitConverter.GetBytes(true);
            replacedertHelper.SequentiallyEqual(arr1, arr2);
        }

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

[Fact]
        public void WriteboolMaxTest()
        {
            var arr1 = new byte[1];
            Serializer.Write(arr1, false);
            var arr2 = BitConverter.GetBytes(false);
            replacedertHelper.SequentiallyEqual(arr1, arr2);
        }

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

public override void Write(bool value) => WriteRaw(BitConverter.GetBytes(value));

19 View Source File : EndianAwareBinaryWriter.cs
License : MIT License
Project Creator : bamcis-io

public void Write(bool value, Endianness endianness) => this.WriteForEndianness(BitConverter.GetBytes(value), endianness);

19 View Source File : LibraCanonicalDeserialization.cs
License : MIT License
Project Creator : blockcoli

public byte[] BoolToByte(bool source)
        {
            return BitConverter.GetBytes(source);
        }

19 View Source File : Ext.cs
License : MIT License
Project Creator : bonzaiferroni

public static byte [] ToByteArray<T> (this T value, ByteOrder order)
      where T : struct
    {
      var type = typeof (T);
      var bytes = type == typeof (Boolean)
                ? BitConverter.GetBytes ((Boolean)(object) value)
                : type == typeof (Byte)
                  ? new byte [] { (Byte)(object) value }
                  : type == typeof (Char)
                    ? BitConverter.GetBytes ((Char)(object) value)
                    : type == typeof (Double)
                      ? BitConverter.GetBytes ((Double)(object) value)
                      : type == typeof (Int16)
                        ? BitConverter.GetBytes ((Int16)(object) value)
                        : type == typeof (Int32)
                          ? BitConverter.GetBytes ((Int32)(object) value)
                          : type == typeof (Int64)
                            ? BitConverter.GetBytes ((Int64)(object) value)
                            : type == typeof (Single)
                              ? BitConverter.GetBytes ((Single)(object) value)
                              : type == typeof (UInt16)
                                ? BitConverter.GetBytes ((UInt16)(object) value)
                                : type == typeof (UInt32)
                                  ? BitConverter.GetBytes ((UInt32)(object) value)
                                  : type == typeof (UInt64)
                                    ? BitConverter.GetBytes ((UInt64)(object) value)
                                    : new byte [0];

      if (bytes.Length > 1 && !order.IsHostOrder ())
        Array.Reverse (bytes);

      return bytes;
    }

19 View Source File : DriverRunner.cs
License : Apache License 2.0
Project Creator : cdy816

protected byte[] ConvertToBytes(object value,byte valuetype)
        {
            switch ((TagType)valuetype)
            {
                case TagType.Bool:
                    return BitConverter.GetBytes((bool)value);
                case TagType.Byte:
                    return BitConverter.GetBytes(Convert.ToByte(value));
                case TagType.DateTime:
                    return BitConverter.GetBytes(Convert.ToInt64(value));
                case TagType.Double:
                    return BitConverter.GetBytes(Convert.ToDouble(value));
                case TagType.Float:
                    return BitConverter.GetBytes(Convert.ToSingle(value));
                case TagType.Int:
                    return BitConverter.GetBytes(Convert.ToInt32(value));
                case TagType.Long:
                    return BitConverter.GetBytes(Convert.ToInt64(value));
                case TagType.Short:
                    return BitConverter.GetBytes(Convert.ToInt16(value));
                case TagType.String:
                    return Encoding.UTF8.GetBytes(value.ToString());
                case TagType.UInt:
                    return BitConverter.GetBytes(Convert.ToUInt32(value));
                case TagType.ULong:
                    return BitConverter.GetBytes(Convert.ToUInt64(value));
                case TagType.UShort:
                    return BitConverter.GetBytes(Convert.ToUInt16(value));
                case TagType.IntPoint:
                    IntPoint ival = (IntPoint)value;
                    byte[] val = new byte[8];
                    BitConverter.GetBytes(ival.X).CopyTo(val, 0);
                    BitConverter.GetBytes(ival.Y).CopyTo(val, 4);
                    return val;
                case TagType.IntPoint3:
                    IntPoint3 ival3 = (IntPoint3)value;
                    val = new byte[12];
                    BitConverter.GetBytes(ival3.X).CopyTo(val, 0);
                    BitConverter.GetBytes(ival3.Y).CopyTo(val, 4);
                    BitConverter.GetBytes(ival3.Z).CopyTo(val, 8);
                    return val;
                case TagType.UIntPoint3:
                    UIntPoint3 uival3 = (UIntPoint3)value;
                    val = new byte[12];
                    BitConverter.GetBytes(uival3.X).CopyTo(val, 0);
                    BitConverter.GetBytes(uival3.Y).CopyTo(val, 4);
                    BitConverter.GetBytes(uival3.Z).CopyTo(val, 8);
                    return val;
                case TagType.UIntPoint:
                    UIntPoint uival = (UIntPoint)value;
                    val = new byte[8];
                    BitConverter.GetBytes(uival.X).CopyTo(val, 0);
                    BitConverter.GetBytes(uival.Y).CopyTo(val, 4);
                    return val;
                case TagType.LongPoint:
                    LongPoint lval = (LongPoint)value;
                    val = new byte[16];
                    BitConverter.GetBytes(lval.X).CopyTo(val, 0);
                    BitConverter.GetBytes(lval.Y).CopyTo(val, 8);
                    return val;
                case TagType.LongPoint3:
                    LongPoint3 lval3 = (LongPoint3)value;
                    val = new byte[24];
                    BitConverter.GetBytes(lval3.X).CopyTo(val, 0);
                    BitConverter.GetBytes(lval3.Y).CopyTo(val, 8);
                    BitConverter.GetBytes(lval3.Z).CopyTo(val, 16);
                    return val;
                case TagType.ULongPoint:
                    ULongPoint ulval = (ULongPoint)value;
                    val = new byte[16];
                    BitConverter.GetBytes(ulval.X).CopyTo(val, 0);
                    BitConverter.GetBytes(ulval.Y).CopyTo(val, 8);
                    return val;
                case TagType.ULongPoint3:
                    ULongPoint3 ulval3 = (ULongPoint3)value;
                    val = new byte[24];
                    BitConverter.GetBytes(ulval3.X).CopyTo(val, 0);
                    BitConverter.GetBytes(ulval3.Y).CopyTo(val, 8);
                    BitConverter.GetBytes(ulval3.Z).CopyTo(val, 16);
                    return val;
            }
            return null;
        }

19 View Source File : PS4DBG.Proc.cs
License : MIT License
Project Creator : ChendoChap

public List<ulong> ScanProcess<T>(int pid, ScanCompareType compareType, T value, T extraValue = default)
        {
            CheckConnected();

            int typeLength = 0;
            ScanValueType valueType;
            byte[] valueBuffer, extraValueBuffer = null;

            // fill in variables
            switch (value)
            {
                case bool b:
                    valueType = ScanValueType.valTypeUInt8;
                    typeLength = 1;
                    valueBuffer = BitConverter.GetBytes(b);
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((bool)(object)extraValue);
                    break;
                case sbyte sb:
                    valueType = ScanValueType.valTypeInt8;
                    valueBuffer = BitConverter.GetBytes(sb);
                    typeLength = 1;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((sbyte)(object)extraValue);
                    break;
                case byte b:
                    valueType = ScanValueType.valTypeUInt8;
                    valueBuffer = BitConverter.GetBytes(b);
                    typeLength = 1;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((byte)(object)extraValue);
                    break;
                case short s:
                    valueType = ScanValueType.valTypeInt16;
                    valueBuffer = BitConverter.GetBytes(s);
                    typeLength = 2;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((short)(object)extraValue);
                    break;
                case ushort us:
                    valueType = ScanValueType.valTypeUInt16;
                    valueBuffer = BitConverter.GetBytes(us);
                    typeLength = 2;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((ushort)(object)extraValue);
                    break;
                case int i:
                    valueType = ScanValueType.valTypeInt32;
                    valueBuffer = BitConverter.GetBytes(i);
                    typeLength = 4;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((int)(object)extraValue);
                    break;
                case uint ui:
                    valueType = ScanValueType.valTypeUInt32;
                    valueBuffer = BitConverter.GetBytes(ui);
                    typeLength = 4;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((uint)(object)extraValue);
                    break;
                case long l:
                    valueType = ScanValueType.valTypeInt64;
                    valueBuffer = BitConverter.GetBytes(l);
                    typeLength = 8;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((long)(object)extraValue);
                    break;
                case ulong ul:
                    valueType = ScanValueType.valTypeUInt64;
                    valueBuffer = BitConverter.GetBytes(ul);
                    typeLength = 8;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((ulong)(object)extraValue);
                    break;
                case float f:
                    valueType = ScanValueType.valTypeFloat;
                    valueBuffer = BitConverter.GetBytes(f);
                    typeLength = 4;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((float)(object)extraValue);
                    break;
                case double d:
                    valueType = ScanValueType.valTypeDouble;
                    valueBuffer = BitConverter.GetBytes(d);
                    typeLength = 8;
                    if (extraValue != null)
                        extraValueBuffer = BitConverter.GetBytes((double)(object)extraValue);
                    break;
                case string s:
                    valueType = ScanValueType.valTypeString;
                    valueBuffer = Encoding.ASCII.GetBytes(s);
                    typeLength = valueBuffer.Length;
                    break;
                case byte[] ba:
                    valueType = ScanValueType.valTypeArrBytes;
                    valueBuffer = ba;
                    typeLength = valueBuffer.Length;
                    break;
                default:
                    throw new NotSupportedException("Requested scan value type is not supported! (Feed in Byte[] instead.)");
                    
            }
            // send packet
            SendCMDPacket(CMDS.CMD_PROC_SCAN, CMD_PROC_SCAN_PACKET_SIZE, pid, (byte)valueType, (byte)compareType, (int)(extraValue == null ? typeLength : typeLength * 2));
            CheckStatus();

            SendData(valueBuffer, typeLength);
            if (extraValueBuffer != null)
            {
                SendData(extraValueBuffer, typeLength);
            }

            CheckStatus();

            // receive results
            int save = sock.ReceiveTimeout;
            sock.ReceiveTimeout = Int32.MaxValue;
            List<ulong> results = new List<ulong>();
            while(true)
            {
                ulong result = BitConverter.ToUInt64(ReceiveData(sizeof(ulong)), 0);
                if(result == 0xFFFFFFFFFFFFFFFF)
                {
                    break;
                }

                results.Add(result);
            }

            sock.ReceiveTimeout = save;

            return results;
        }

19 View Source File : DictionaryObject.cs
License : GNU General Public License v3.0
Project Creator : CircuitLord

public static bool TryChangeType(object input, Type conversionType, IFormatProvider provider, out object value)
        {
            if (conversionType == null)
                throw new ArgumentNullException(nameof(conversionType));

            if (conversionType == typeof(object))
            {
                value = input;
                return true;
            }

            Type nullableType = null;
            if (conversionType.IsNullable())
            {
                nullableType = conversionType.GenericTypeArguments[0];
                if (input == null)
                {
                    value = null;
                    return true;
                }

                return TryChangeType(input, nullableType, provider, out value);
            }

            value = conversionType.IsValueType ? Activator.CreateInstance(conversionType) : null;
            if (input == null)
                return !conversionType.IsValueType;

            var inputType = input.GetType();
            if (inputType.IsreplacedignableFrom(conversionType))
            {
                value = input;
                return true;
            }

            if (conversionType.IsEnum)
                return EnumTryParse(conversionType, input, out value);

            if (conversionType == typeof(Guid))
            {
                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 16)
                        return false;

                    value = new Guid(bytes);
                    return true;
                }

                string svalue = string.Format(provider, "{0}", input).Nullify();
                if (svalue != null && Guid.TryParse(svalue, out Guid guid))
                {
                    value = guid;
                    return true;
                }
                return false;
            }

            if (conversionType == typeof(IntPtr))
            {
                if (IntPtr.Size == 8)
                {
                    if (TryChangeType(input, provider, out long l))
                    {
                        value = new IntPtr(l);
                        return true;
                    }
                }
                else if (TryChangeType(input, provider, out int i))
                {
                    value = new IntPtr(i);
                    return true;
                }
                return false;
            }

            if (conversionType == typeof(bool))
            {
                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 1)
                        return false;

                    value = BitConverter.ToBoolean(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(int))
            {
                if (inputType == typeof(uint))
                {
                    value = unchecked((int)(uint)input);
                    return true;
                }

                if (inputType == typeof(ulong))
                {
                    value = unchecked((int)(ulong)input);
                    return true;
                }

                if (inputType == typeof(ushort))
                {
                    value = unchecked((int)(ushort)input);
                    return true;
                }

                if (inputType == typeof(byte))
                {
                    value = unchecked((int)(byte)input);
                    return true;
                }

                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 4)
                        return false;

                    value = BitConverter.ToInt32(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(long))
            {
                if (inputType == typeof(uint))
                {
                    value = unchecked((long)(uint)input);
                    return true;
                }

                if (inputType == typeof(ulong))
                {
                    value = unchecked((long)(ulong)input);
                    return true;
                }

                if (inputType == typeof(ushort))
                {
                    value = unchecked((long)(ushort)input);
                    return true;
                }

                if (inputType == typeof(byte))
                {
                    value = unchecked((long)(byte)input);
                    return true;
                }

                if (inputType == typeof(DateTime))
                {
                    value = ((DateTime)input).Ticks;
                    return true;
                }

                if (inputType == typeof(TimeSpan))
                {
                    value = ((TimeSpan)input).Ticks;
                    return true;
                }

                if (inputType == typeof(DateTimeOffset))
                {
                    value = ((DateTimeOffset)input).Ticks;
                    return true;
                }

                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 8)
                        return false;

                    value = BitConverter.ToInt64(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(short))
            {
                if (inputType == typeof(uint))
                {
                    value = unchecked((short)(uint)input);
                    return true;
                }

                if (inputType == typeof(ulong))
                {
                    value = unchecked((short)(ulong)input);
                    return true;
                }

                if (inputType == typeof(ushort))
                {
                    value = unchecked((short)(ushort)input);
                    return true;
                }

                if (inputType == typeof(byte))
                {
                    value = unchecked((short)(byte)input);
                    return true;
                }

                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 2)
                        return false;

                    value = BitConverter.ToInt16(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(sbyte))
            {
                if (inputType == typeof(uint))
                {
                    value = unchecked((sbyte)(uint)input);
                    return true;
                }

                if (inputType == typeof(ulong))
                {
                    value = unchecked((sbyte)(ulong)input);
                    return true;
                }

                if (inputType == typeof(ushort))
                {
                    value = unchecked((sbyte)(ushort)input);
                    return true;
                }

                if (inputType == typeof(byte))
                {
                    value = unchecked((sbyte)(byte)input);
                    return true;
                }

                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 1)
                        return false;

                    value = unchecked((sbyte)bytes[0]);
                    return true;
                }
            }

            if (conversionType == typeof(uint))
            {
                if (inputType == typeof(int))
                {
                    value = unchecked((uint)(int)input);
                    return true;
                }

                if (inputType == typeof(long))
                {
                    value = unchecked((uint)(long)input);
                    return true;
                }

                if (inputType == typeof(short))
                {
                    value = unchecked((uint)(short)input);
                    return true;
                }

                if (inputType == typeof(sbyte))
                {
                    value = unchecked((uint)(sbyte)input);
                    return true;
                }

                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 4)
                        return false;

                    value = BitConverter.ToUInt32(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(ulong))
            {
                if (inputType == typeof(int))
                {
                    value = unchecked((ulong)(int)input);
                    return true;
                }

                if (inputType == typeof(long))
                {
                    value = unchecked((ulong)(long)input);
                    return true;
                }

                if (inputType == typeof(short))
                {
                    value = unchecked((ulong)(short)input);
                    return true;
                }

                if (inputType == typeof(sbyte))
                {
                    value = unchecked((ulong)(sbyte)input);
                    return true;
                }

                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 8)
                        return false;

                    value = BitConverter.ToUInt64(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(ushort))
            {
                if (inputType == typeof(int))
                {
                    value = unchecked((ushort)(int)input);
                    return true;
                }

                if (inputType == typeof(long))
                {
                    value = unchecked((ushort)(long)input);
                    return true;
                }

                if (inputType == typeof(short))
                {
                    value = unchecked((ushort)(short)input);
                    return true;
                }

                if (inputType == typeof(sbyte))
                {
                    value = unchecked((ushort)(sbyte)input);
                    return true;
                }

                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 2)
                        return false;

                    value = BitConverter.ToUInt16(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(byte))
            {
                if (inputType == typeof(int))
                {
                    value = unchecked((byte)(int)input);
                    return true;
                }

                if (inputType == typeof(long))
                {
                    value = unchecked((byte)(long)input);
                    return true;
                }

                if (inputType == typeof(short))
                {
                    value = unchecked((byte)(short)input);
                    return true;
                }

                if (inputType == typeof(sbyte))
                {
                    value = unchecked((byte)(sbyte)input);
                    return true;
                }

                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 1)
                        return false;

                    value = bytes[0];
                    return true;
                }
            }

            if (conversionType == typeof(decimal))
            {
                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 16)
                        return false;

                    value = ToDecimal(bytes);
                    return true;
                }
            }

            if (conversionType == typeof(DateTime))
            {
                if (inputType == typeof(long))
                {
                    value = new DateTime((long)input);
                    return true;
                }

                if (inputType == typeof(DateTimeOffset))
                {
                    value = ((DateTimeOffset)input).DateTime;
                    return true;
                }
            }

            if (conversionType == typeof(TimeSpan))
            {
                if (inputType == typeof(long))
                {
                    value = new TimeSpan((long)input);
                    return true;
                }
            }

            if (conversionType == typeof(char))
            {
                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 2)
                        return false;

                    value = BitConverter.ToChar(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(float))
            {
                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 4)
                        return false;

                    value = BitConverter.ToSingle(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(double))
            {
                if (inputType == typeof(byte[]))
                {
                    var bytes = (byte[])input;
                    if (bytes.Length != 8)
                        return false;

                    value = BitConverter.ToDouble(bytes, 0);
                    return true;
                }
            }

            if (conversionType == typeof(DateTimeOffset))
            {
                if (inputType == typeof(DateTime))
                {
                    value = new DateTimeOffset((DateTime)input);
                    return true;
                }

                if (inputType == typeof(long))
                {
                    value = new DateTimeOffset(new DateTime((long)input));
                    return true;
                }
            }

            if (conversionType == typeof(byte[]))
            {
                if (inputType == typeof(int))
                {
                    value = BitConverter.GetBytes((int)input);
                    return true;
                }

                if (inputType == typeof(long))
                {
                    value = BitConverter.GetBytes((long)input);
                    return true;
                }

                if (inputType == typeof(short))
                {
                    value = BitConverter.GetBytes((short)input);
                    return true;
                }

                if (inputType == typeof(uint))
                {
                    value = BitConverter.GetBytes((uint)input);
                    return true;
                }

                if (inputType == typeof(ulong))
                {
                    value = BitConverter.GetBytes((ulong)input);
                    return true;
                }

                if (inputType == typeof(ushort))
                {
                    value = BitConverter.GetBytes((ushort)input);
                    return true;
                }

                if (inputType == typeof(bool))
                {
                    value = BitConverter.GetBytes((bool)input);
                    return true;
                }

                if (inputType == typeof(char))
                {
                    value = BitConverter.GetBytes((char)input);
                    return true;
                }

                if (inputType == typeof(float))
                {
                    value = BitConverter.GetBytes((float)input);
                    return true;
                }

                if (inputType == typeof(double))
                {
                    value = BitConverter.GetBytes((double)input);
                    return true;
                }

                if (inputType == typeof(byte))
                {
                    value = new byte[] { (byte)input };
                    return true;
                }

                if (inputType == typeof(sbyte))
                {
                    value = new byte[] { unchecked((byte)(sbyte)input) };
                    return true;
                }

                if (inputType == typeof(decimal))
                {
                    value = ((decimal)value).ToBytes();
                    return true;
                }

                if (inputType == typeof(Guid))
                {
                    value = ((Guid)input).ToByteArray();
                    return true;
                }
            }

            var tc = TypeDescriptor.GetConverter(conversionType);
            if (tc != null && tc.CanConvertFrom(inputType))
            {
                try
                {
                    value = tc.ConvertFrom(null, provider as CultureInfo, input);
                    return true;
                }
                catch
                {
                    // continue;
                }
            }

            tc = TypeDescriptor.GetConverter(inputType);
            if (tc != null && tc.CanConvertTo(conversionType))
            {
                try
                {
                    value = tc.ConvertTo(null, provider as CultureInfo, input, conversionType);
                    return true;
                }
                catch
                {
                    // continue;
                }
            }

            if (input is IConvertible convertible)
            {
                try
                {
                    value = convertible.ToType(conversionType, provider);
                    return true;
                }
                catch
                {
                    // continue
                }
            }

            if (conversionType == typeof(string))
            {
                value = string.Format(provider, "{0}", input);
                return true;
            }

            return false;
        }

19 View Source File : ElectionDialog.cs
License : MIT License
Project Creator : CityOfZion

public StateTransaction GetTransaction()
        {
            ECPoint pubkey = (ECPoint)comboBox1.SelectedItem;
            return Program.CurrentWallet.MakeTransaction(new StateTransaction
            {
                Version = 0,
                Descriptors = new[]
                {
                    new StateDescriptor
                    {
                        Type = StateType.Validator,
                        Key = pubkey.ToArray(),
                        Field = "Registered",
                        Value = BitConverter.GetBytes(true)
                    }
                }
            });
        }

19 View Source File : ElectionDialog.cs
License : MIT License
Project Creator : CityOfZion

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex >= 0)
            {
                button1.Enabled = true;
                ECPoint pubkey = (ECPoint)comboBox1.SelectedItem;
                StateTransaction tx = new StateTransaction
                {
                    Version = 0,
                    Descriptors = new[]
                    {
                        new StateDescriptor
                        {
                            Type = StateType.Validator,
                            Key = pubkey.ToArray(),
                            Field = "Registered",
                            Value = BitConverter.GetBytes(true)
                        }
                    }
                };
                label3.Text = $"{tx.SystemFee} gas";
            }
        }

19 View Source File : SessionHelper.cs
License : Apache License 2.0
Project Creator : crazyants

public static void SetBoolean(this ISession session, string key, bool value)
        {
            session.Set(key, BitConverter.GetBytes(value));
        }

19 View Source File : AuthenticationPackets.cs
License : GNU General Public License v3.0
Project Creator : CypherCore

public override void Write()
        {
            HmacSha256 hash = new(EncryptionKey);
            hash.Process(BitConverter.GetBytes(Enabled), 1);
            hash.Finish(EnableEncryptionSeed, 16);

            _worldPacket.WriteBytes(RsaCrypt.RSA.SignHash(hash.Digest, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1).Reverse().ToArray());
            _worldPacket.WriteBit(Enabled);
            _worldPacket.FlushBits();
        }

19 View Source File : ByteBuffer.cs
License : Apache License 2.0
Project Creator : eedalong

public void AddBool(bool value)
        {
            var boolBuffer = BitConverter.GetBytes(value);
            
            if (_isLittleEndian) boolBuffer = boolBuffer.Reverse().ToArray();

            ExtendBuffer(boolBuffer.Length);
            boolBuffer.CopyTo(_buffer, _writePos);
            _writePos += boolBuffer.Length;
        }

19 View Source File : Packet.cs
License : GNU General Public License v3.0
Project Creator : Extremelyd1

public void Write(bool value) {
            _buffer.AddRange(BitConverter.GetBytes(value));
        }

19 View Source File : BooleanProxy.cs
License : MIT License
Project Creator : FICTURE7

public static void Serialize(Stream bytes, bool instance)
		{
			byte[] buffer = BitConverter.GetBytes(instance);
			bytes.Write(buffer, 0, buffer.Length);
		}

19 View Source File : Packet.cs
License : MIT License
Project Creator : Filigrani

public void Write(bool _value)
        {
            buffer.AddRange(BitConverter.GetBytes(_value));
        }

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

public byte[] GetBytes(bool value)
		{
			return BitConverter.GetBytes(value);
		}

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

private bool ReverseValue(bool value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            Array.Reverse(bytes);
            return BitConverter.ToBoolean(bytes, 0);
        }

19 View Source File : ByteBuffer.cs
License : MIT License
Project Creator : ialex32x

public void WriteBoolean(bool value)
        {
            WriteBytes(BitConverter.GetBytes(value));
        }

19 View Source File : DataConverter.cs
License : MIT License
Project Creator : iothua

public static string GetString(bool value)
        {
            return Convert.ToBase64String(BitConverter.GetBytes(value));
        }

19 View Source File : Packer.cs
License : MIT License
Project Creator : iwiniwin

public static void WriteBool(bool b) 
        {
            m_Data.Push(BitConverter.GetBytes(b));
        }

19 View Source File : Packet.cs
License : MIT License
Project Creator : jngo102

public void Write(bool value)
        {
            buffer.AddRange(BitConverter.GetBytes(value));
        }

19 View Source File : Memory.cs
License : MIT License
Project Creator : katalash

public static bool WriteBoolean(IntPtr address, bool value)
        {
            return Kernel32.WriteProcessMemory(ProcessHandle, address, BitConverter.GetBytes(value), (UIntPtr)1, UIntPtr.Zero);
        }

19 View Source File : TcpDebugControllerBase.cs
License : Apache License 2.0
Project Creator : KHCmaster

protected void WriteBoolean(PPDPackStreamWriter writer, bool value)
        {
            var writeData = BitConverter.GetBytes(value);
            writer.Write(writeData, 0, writeData.Length);
        }

19 View Source File : Ext.cs
License : MIT License
Project Creator : kodai100

public static byte[] ToByteArray<T> (this T value, ByteOrder order)
      where T : struct
    {
      var type = typeof (T);
      var bytes = type == typeof (Boolean)
                  ? BitConverter.GetBytes ((Boolean)(object) value)
                  : type == typeof (Byte)
                    ? new byte[] { (Byte)(object) value }
                    : type == typeof (Char)
                      ? BitConverter.GetBytes ((Char)(object) value)
                      : type == typeof (Double)
                        ? BitConverter.GetBytes ((Double)(object) value)
                        : type == typeof (Int16)
                          ? BitConverter.GetBytes ((Int16)(object) value)
                          : type == typeof (Int32)
                            ? BitConverter.GetBytes ((Int32)(object) value)
                            : type == typeof (Int64)
                              ? BitConverter.GetBytes ((Int64)(object) value)
                              : type == typeof (Single)
                                ? BitConverter.GetBytes ((Single)(object) value)
                                : type == typeof (UInt16)
                                  ? BitConverter.GetBytes ((UInt16)(object) value)
                                  : type == typeof (UInt32)
                                    ? BitConverter.GetBytes ((UInt32)(object) value)
                                    : type == typeof (UInt64)
                                      ? BitConverter.GetBytes ((UInt64)(object) value)
                                      : WebSocket.EmptyBytes;

      if (bytes.Length > 1 && !order.IsHostOrder ())
        Array.Reverse (bytes);

      return bytes;
    }

19 View Source File : MCM.cs
License : GNU General Public License v3.0
Project Creator : Laamy

public static byte[] bool2Bytes(bool value)
        {
            var intByte = BitConverter.GetBytes(value);
            return intByte;
        }

19 View Source File : AsyncBinaryWriter.cs
License : GNU General Public License v3.0
Project Creator : marcinotorowski

public Task WriteBoolAsync(bool boolean, CancellationToken token = default(CancellationToken))
        {
            return this.WriteBytesAsync(BitConverter.GetBytes(boolean), token);
        }

19 View Source File : DefaultConverter.cs
License : MIT License
Project Creator : meziantou

protected virtual bool TryConvert(object? input, Type conversionType, IFormatProvider? provider, out object? value)
        {
            if (conversionType == null)
                throw new ArgumentNullException(nameof(conversionType));

            if (conversionType == typeof(object))
            {
                value = input;
                return true;
            }

            if (input == null || Convert.IsDBNull(input))
            {
                if (conversionType.IsNullableOfT())
                {
                    value = null;
                    return true;
                }

                if (conversionType.IsValueType)
                {
                    value = Activator.CreateInstance(conversionType);
                    return false;
                }

                value = null;
                return true;
            }

            var inputType = input.GetType();
            if (conversionType.IsreplacedignableFrom(inputType.GetTypeInfo()))
            {
                value = input;
                return true;
            }

            if (conversionType.IsNullableOfT())
            {
                // en empty string is successfully converted into a nullable
                var inps = input as string;
                if (string.IsNullOrWhiteSpace(inps))
                {
                    value = null;
                    return true;
                }

                var vtType = Nullable.GetUnderlyingType(conversionType);
                if (vtType != null && TryConvert(input, vtType, provider, out var vtValue))
                {
                    var nt = typeof(Nullable<>).MakeGenericType(vtType);
                    value = Activator.CreateInstance(nt, vtValue);
                    return true;
                }

                value = null;
                return false;
            }

            // enum must be before integers
            if (conversionType.IsEnum)
            {
                if (TryConvertEnum(input, conversionType, provider, out value))
                    return true;
            }

            var conversionCode = Type.GetTypeCode(conversionType);
            switch (conversionCode)
            {
                case TypeCode.Boolean:
                    bool boolValue;
                    if (TryConvert(input, provider, out boolValue))
                    {
                        value = boolValue;
                        return true;
                    }
                    break;

                case TypeCode.Byte:
                    byte byteValue;
                    if (TryConvert(input, provider, out byteValue))
                    {
                        value = byteValue;
                        return true;
                    }
                    break;

                case TypeCode.Char:
                    char charValue;
                    if (TryConvert(input, provider, out charValue))
                    {
                        value = charValue;
                        return true;
                    }
                    break;

                case TypeCode.DateTime:
                    DateTime dtValue;
                    if (TryConvert(input, provider, out dtValue))
                    {
                        value = dtValue;
                        return true;
                    }
                    break;

                case TypeCode.Decimal:
                    decimal decValue;
                    if (TryConvert(input, provider, out decValue))
                    {
                        value = decValue;
                        return true;
                    }
                    break;

                case TypeCode.Double:
                    double dblValue;
                    if (TryConvert(input, provider, out dblValue))
                    {
                        value = dblValue;
                        return true;
                    }
                    break;

                case TypeCode.Int16:
                    short i16Value;
                    if (TryConvert(input, provider, out i16Value))
                    {
                        value = i16Value;
                        return true;
                    }
                    break;

                case TypeCode.Int32:
                    int i32Value;
                    if (TryConvert(input, provider, out i32Value))
                    {
                        value = i32Value;
                        return true;
                    }
                    break;

                case TypeCode.Int64:
                    long i64Value;
                    if (TryConvert(input, provider, out i64Value))
                    {
                        value = i64Value;
                        return true;
                    }
                    break;

                case TypeCode.SByte:
                    sbyte sbyteValue;
                    if (TryConvert(input, provider, out sbyteValue))
                    {
                        value = sbyteValue;
                        return true;
                    }
                    break;

                case TypeCode.Single:
                    float fltValue;
                    if (TryConvert(input, provider, out fltValue))
                    {
                        value = fltValue;
                        return true;
                    }
                    break;

                case TypeCode.String:
                    if (input is byte[] inputBytes)
                    {
                        if (TryConvert(inputBytes, provider, out var str))
                        {
                            value = str;
                            return true;
                        }

                        value = null;
                        return false;
                    }

                    if (input is CultureInfo ci)
                    {
                        value = ci.Name;
                        return true;
                    }

                    var tc = TypeDescriptor.GetConverter(inputType);
                    if (tc != null && tc.CanConvertTo(typeof(string)))
                    {
                        value = (string?)tc.ConvertTo(input, typeof(string));
                        return true;
                    }

                    value = Convert.ToString(input, provider);
                    return true;

                case TypeCode.UInt16:
                    ushort u16Value;
                    if (TryConvert(input, provider, out u16Value))
                    {
                        value = u16Value;
                        return true;
                    }
                    break;

                case TypeCode.UInt32:
                    uint u32Value;
                    if (TryConvert(input, provider, out u32Value))
                    {
                        value = u32Value;
                        return true;
                    }
                    break;

                case TypeCode.UInt64:
                    ulong u64Value;
                    if (TryConvert(input, provider, out u64Value))
                    {
                        value = u64Value;
                        return true;
                    }
                    break;

                case TypeCode.Object:
                    if (conversionType == typeof(Guid))
                    {
                        if (TryConvert(input, provider, out Guid gValue))
                        {
                            value = gValue;
                            return true;
                        }
                    }
                    else if (conversionType == typeof(CultureInfo))
                    {
                        if (TryConvert(input, provider, out CultureInfo? cultureInfo))
                        {
                            value = cultureInfo;
                            return true;
                        }

                        value = null;
                        return false;
                    }
                    else if (conversionType == typeof(DateTimeOffset))
                    {
                        if (TryConvert(input, provider, out DateTimeOffset dto))
                        {
                            value = dto;
                            return true;
                        }
                    }
                    else if (conversionType == typeof(TimeSpan))
                    {
                        if (TryConvert(input, provider, out TimeSpan ts))
                        {
                            value = ts;
                            return true;
                        }
                    }
                    else if (conversionType == typeof(byte[]))
                    {
                        byte[]? bytes;
                        var inputCode = Type.GetTypeCode(inputType);
                        switch (inputCode)
                        {
                            case TypeCode.DBNull:
                                value = null;
                                return true;

                            case TypeCode.Boolean:
                                value = BitConverter.GetBytes((bool)input);
                                return true;

                            case TypeCode.Char:
                                value = BitConverter.GetBytes((char)input);
                                return true;

                            case TypeCode.Double:
                                value = BitConverter.GetBytes((double)input);
                                return true;

                            case TypeCode.Int16:
                                value = BitConverter.GetBytes((short)input);
                                return true;

                            case TypeCode.Int32:
                                value = BitConverter.GetBytes((int)input);
                                return true;

                            case TypeCode.Int64:
                                value = BitConverter.GetBytes((long)input);
                                return true;

                            case TypeCode.Single:
                                value = BitConverter.GetBytes((float)input);
                                return true;

                            case TypeCode.UInt16:
                                value = BitConverter.GetBytes((ushort)input);
                                return true;

                            case TypeCode.UInt32:
                                value = BitConverter.GetBytes((uint)input);
                                return true;

                            case TypeCode.UInt64:
                                value = BitConverter.GetBytes((ulong)input);
                                return true;

                            case TypeCode.Byte:
                                value = new[] { (byte)input };
                                return true;

                            case TypeCode.DateTime:
                                if (TryConvert((DateTime)input, provider, out bytes))
                                {
                                    value = bytes;
                                    return true;
                                }
                                value = null;
                                return false;

                            case TypeCode.Decimal:
                                if (TryConvert((decimal)input, provider, out bytes))
                                {
                                    value = bytes;
                                    return true;
                                }

                                value = null;
                                return false;

                            case TypeCode.SByte:
                                value = new[] { unchecked((byte)input) };
                                return true;

                            case TypeCode.String:
                                if (TryConvert((string)input, provider, out bytes))
                                {
                                    value = bytes;
                                    return true;
                                }

                                value = null;
                                return false;

                            default:
                                if (TryConvert(input, provider, out bytes))
                                {
                                    value = bytes;
                                    return true;
                                }
                                break;
                        }
                    }
                    break;
            }

            // catch many exceptions before they happen
            if (IsNumberType(conversionType) && IsNullOrEmptyString(input))
            {
                value = Activator.CreateInstance(conversionType);
                return false;
            }

            TypeConverter? ctConverter = null;
            try
            {
                ctConverter = TypeDescriptor.GetConverter(conversionType);
                if (ctConverter != null && ctConverter.CanConvertFrom(inputType))
                {
                    if (provider is CultureInfo cultureInfo)
                    {
                        value = ctConverter.ConvertFrom(context: null, cultureInfo, input);
                    }
                    else
                    {
                        value = ctConverter.ConvertFrom(input);
                    }

                    return true;
                }
            }
            catch
            {
                // do nothing
            }

            try
            {
                var inputConverter = TypeDescriptor.GetConverter(inputType);
                if (inputConverter != null && inputConverter.CanConvertTo(conversionType))
                {
                    value = inputConverter.ConvertTo(context: null, provider as CultureInfo, input, conversionType);
                    return true;
                }
            }
            catch
            {
                // do nothing
            }

            var defaultValue = conversionType.IsValueType ? Activator.CreateInstance(conversionType) : null;
            try
            {
                if (ctConverter != null && !(input is string) && ctConverter.CanConvertFrom(typeof(string)))
                {
                    value = ctConverter.ConvertFrom(context: null, provider as CultureInfo, Convert.ToString(input, provider)!);
                    return true;
                }
            }
            catch
            {
                // do nothing
            }

            if (TryConvertUsingImplicitConverter(input, conversionType, provider, out value))
                return true;

            value = defaultValue;
            return false;
        }

19 View Source File : Ext.cs
License : Apache License 2.0
Project Creator : micro-chen

public static byte[] ToBytes<T>(T value, ByteOrder order)
          where T : struct
        {
            var type = typeof(T);
            byte[] buffer;
            if (type == typeof(Boolean))
            {
                buffer = BitConverter.GetBytes((Boolean)(object)value);
            }
            else if (type == typeof(Char))
            {
                buffer = BitConverter.GetBytes((Char)(object)value);
            }
            else if (type == typeof(Double))
            {
                buffer = BitConverter.GetBytes((Double)(object)value);
            }
            else if (type == typeof(Int16))
            {
                buffer = BitConverter.GetBytes((Int16)(object)value);
            }
            else if (type == typeof(Int32))
            {
                buffer = BitConverter.GetBytes((Int32)(object)value);
            }
            else if (type == typeof(Int64))
            {
                buffer = BitConverter.GetBytes((Int64)(object)value);
            }
            else if (type == typeof(Single))
            {
                buffer = BitConverter.GetBytes((Single)(object)value);
            }
            else if (type == typeof(UInt16))
            {
                buffer = BitConverter.GetBytes((UInt16)(object)value);
            }
            else if (type == typeof(UInt32))
            {
                buffer = BitConverter.GetBytes((UInt32)(object)value);
            }
            else if (type == typeof(UInt64))
            {
                buffer = BitConverter.GetBytes((UInt64)(object)value);
            }
            else
            {
                buffer = new byte[] { };
            }

            return buffer.Length == 0 || IsHostOrder(order)
                   ? buffer
                   : Reverse(buffer);
        }

19 View Source File : LittleEndianBitConverter.cs
License : Apache License 2.0
Project Creator : micro-chen

static public byte[] GetBytes(bool value)
        {
            byte[] ret = BitConverter.GetBytes(value);
            ReverseBytes(ret, 0, ret.Length);
            return ret;
        }

19 View Source File : MakeKeyHelpersTests.cs
License : MIT License
Project Creator : microsoft

private void MakeKeyBooleanHelper(bool expected)
        {
            this.CreateTempTableOnColumn("boolean");
            this.InsertRecord(BitConverter.GetBytes(expected));
            Api.MakeKey(this.sesid, this.tableid, expected, MakeKeyGrbit.NewKey);
            replacedert.IsTrue(Api.TrySeek(this.sesid, this.tableid, SeekGrbit.SeekEQ));
            bool actual = (bool)Api.RetrieveColumnAsBoolean(this.sesid, this.tableid, this.columnid);
            replacedert.AreEqual(expected, actual);
        }

19 View Source File : converter.cs
License : MIT License
Project Creator : microsoft

public static byte[] BytesFromObject(JET_coltyp type, bool isASCII, object o)
        {
            if (o is DBNull)
            {
                return null;
            }

            if (null == o)
            {
                return null;
            }

            switch (type)
            {
                case JET_coltyp.Nil:
                    throw new ArgumentOutOfRangeException("type", "Nil is not valid");
                case JET_coltyp.Bit:
                    return BitConverter.GetBytes(Convert.ToBoolean(o));
                case JET_coltyp.UnsignedByte:
                    byte[] bytes = new byte[1];
                    bytes[0] = (byte)o;
                    return bytes;
                case JET_coltyp.Short:
                    return BitConverter.GetBytes(Convert.ToInt16(o));
                case JET_coltyp.Long:
                    return BitConverter.GetBytes(Convert.ToInt32(o));
                case VistaColtyp.LongLong:
                    return BitConverter.GetBytes(Convert.ToInt64(o));
                case JET_coltyp.Currency:
                    return BitConverter.GetBytes(Convert.ToInt64(o));
                case JET_coltyp.IEEESingle:
                    return BitConverter.GetBytes(Convert.ToSingle(o));
                case JET_coltyp.IEEEDouble:
                    return BitConverter.GetBytes(Convert.ToDouble(o));
                case VistaColtyp.UnsignedShort:
                    return BitConverter.GetBytes(Convert.ToUInt16(o));
                case VistaColtyp.UnsignedLong:
                    return BitConverter.GetBytes(Convert.ToUInt32(o));
                case JET_coltyp.Binary:
                    return (byte[])o;
                case JET_coltyp.LongBinary:
                    return (byte[])o;
                case JET_coltyp.DateTime:
                    // Internally DateTime is stored as a double, mapping to a COLEDateTime
                    DateTime datetime = Convert.ToDateTime(o);
                    double oleDateTime = datetime.ToOADate();
                    return BitConverter.GetBytes(oleDateTime);
                case JET_coltyp.Text:
                    if (isASCII)
                    {
                        return Encoding.ASCII.GetBytes(o.ToString());
                    }
                    else
                    {
                        return Encoding.Unicode.GetBytes(o.ToString());
                    }

                case JET_coltyp.LongText:
                    if (isASCII)
                    {
                        return Encoding.ASCII.GetBytes(o.ToString());
                    }
                    else
                    {
                        return Encoding.Unicode.GetBytes(o.ToString());
                    }

                case VistaColtyp.GUID:
                    if (o is string)
                    {
                        Guid guid = new Guid((string)o);
                        return guid.ToByteArray();
                    }
                    else if (o is byte[])
                    {
                        Guid guid = new Guid((byte[])o);
                        return guid.ToByteArray();
                    }
                    else
                    {
                        // if o isn't a Guid, this will throw an exception
                        return ((Guid)o).ToByteArray();
                    }

                default:
                    throw new ArgumentOutOfRangeException("type", "unknown type");
            }
        }

19 View Source File : Binary.cs
License : GNU Lesser General Public License v3.0
Project Creator : MineCoreDev

public static void WriteBool(ref MemorySpan span, bool value)
        {
            byte[] bytes = BitConverter.GetBytes(value);

            span.WriteBytes(bytes);
        }

19 View Source File : Communicator.cs
License : MIT License
Project Creator : Mohelm97

public void WriteBool (bool value)
        {
            pipe.Write (BitConverter.GetBytes (value), 0, 1);
        }

19 View Source File : ByteArray.cs
License : MIT License
Project Creator : moto2002

public void Write(bool value)
    {
        byte[] bytes = BitConverter.GetBytes(value);
        this.Write(bytes, 0, bytes.Length);
    }

19 View Source File : Writer.cs
License : MIT License
Project Creator : mrdav30

public void Write (bool value)
		{
			Canvas.AddRange (BitConverter.GetBytes (value));
		}

19 View Source File : zprotowire.cs
License : GNU General Public License v3.0
Project Creator : Navy1987

protected int write(ref dll.args arg, bool val) {
			byte[] src = BitConverter.GetBytes(val);
 			return write(ref arg, src);
		}

19 View Source File : EndianBitConverter.cs
License : Apache License 2.0
Project Creator : nesfit

public byte[] GetBytes(bool value) { return BitConverter.GetBytes(value); }

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

public static void Write(this BinaryWriter writer, bool value, int nativeSize)
		{
			Write(writer, BitConverter.GetBytes(value), nativeSize);
		}

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

private void encodeBool(MemoryStream ms, bool v)
        {
            byte[] buf = BitConverter.GetBytes(v);
            ms.Write(buf, 0, buf.Length);
        }

19 View Source File : BinaryAnnotationValueEncoder.cs
License : Apache License 2.0
Project Creator : openzipkin

public static byte[] Encode(bool value)
        {
            return BitConverter.GetBytes(value);
        }

19 View Source File : BinaryBuffer.cs
License : GNU General Public License v2.0
Project Creator : OwlGamingCommunity

public void WriteBool(bool b)
	{
		WriteToBuffer(BitConverter.GetBytes(b));
	}

19 View Source File : FVariantData.cs
License : MIT License
Project Creator : pixeltris

public void SetValue(bool data)
        {
            Type = EOnlineKeyValuePairDataType.Bool;
            Data = BitConverter.GetBytes(data);
        }

19 View Source File : EndianBitConverter.cs
License : MIT License
Project Creator : proepkes

public byte[] GetBytes(bool value)
        {
            return BitConverter.GetBytes(value);
        }

19 View Source File : NistLibSpec.cs
License : Apache License 2.0
Project Creator : ProteoWizard

private bool CreateCache(ILoadMonitor loader, IProgressStatus status, int percent, out string warning)
        {
            var sm = loader.StreamManager;
            long size = sm.GetLength(FilePath);
            
            long readChars = 0;
            var knownKeys = new HashSet<LibKey>();
            var ambiguousKeys = new HashSet<LibKey>();
            warning = null;

            using (TextReader reader = sm.CreateReader(FilePath))
            using (FileSaver fs = new FileSaver(CachePath, sm))
            using (Stream outStream = sm.CreateStream(fs.SafeName, FileMode.Create, true))
            {
                var libraryEntries = new List<NistSpectrumInfo>(10000);

                long lineCount = 0;
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    lineCount++;

                    // Update status trying to approximate position in the file
                    readChars += line.Length;
                    int percentComplete = (int) (readChars * percent / size);
                    if (status.PercentComplete != percentComplete)
                    {
                        // Check for cancellation after each integer change in percent loaded.
                        if (loader.IsCanceled)
                        {
                            loader.UpdateProgress(status.Cancel());
                            return false;
                        }

                        // If not cancelled, update progress.
                        loader.UpdateProgress(status = status.ChangePercentComplete(percentComplete));
                    }

                    // Handle quirky line construction by mzVault msp export
                    line = HandleMzVaultLineVariant(line, out _);

                    // Read until name line
                    if (!line.StartsWith(NAME, StringComparison.InvariantCultureIgnoreCase)) // Accept Name:, NAME:, nAmE: etc
                        continue;
                    Match match = REGEX_NAME.Match(line);
                    var isPeptide = true;
                    var mzMatchTolerance = DEFAULT_MZ_MATCH_TOLERANCE;  
                    var isGC = false;
                    if (!match.Success)
                    {
                        isPeptide = false;
                        match = REGEX_NAME_SMALLMOL.Match(line);
                    }
                    if (!match.Success)
                        continue;

                    string sequence = match.Groups[1].Value; // Peptide sequence or molecule name
                    var charge = isPeptide ? int.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture) : 0;
                    var adduct = Adduct.EMPTY;
                    string formula = null;
                    var otherKeys = new Dictionary<string, string>();
                    string inChiKey = null;
                    string inChi = null;
                    string CAS = null;
                    string KEGG = null;
                    string SMILES = null;

                    int numPeaksDeclared = 0;
                    float? tfRatio = null;
                    double? rt = null, irt = null;
                    int? copies = null;
                    double? precursorMz = null;
                    bool? isPositive = null;

                    // Process until the start of the peaks
                    while ((line = reader.ReadLine()) != null)
                    {
                        lineCount++;

                        readChars += line.Length;
                        line = HandleMzVaultLineVariant(line, out var isMzVault);

                        if (isPeptide && line.StartsWith(SYNON, StringComparison.InvariantCultureIgnoreCase)) // Case insensitive
                        {
                            isPeptide = false;
                        }

                        if (!rt.HasValue)
                        {
                            match = REGEX_RT_LINE.Match(line); // RT may also be found in comments (originally only in comments)
                            if (match.Success)
                            {
                                rt = GetRetentionTime(match.Groups[2].Value, isMzVault || !string.IsNullOrEmpty(match.Groups[1].Value)); // RetentionTime: vs RetentionTimeMins:
                                continue;
                            }

                            match = REGEX_RI_LINE.Match(line);
                            if (!match.Success)
                                match = REGEX_RI.Match(line);
                            if (match.Success)
                            {
                                // Note using RT as stand-in for RI (retention Time vs retention Index, LC vs GC)
                                // CONSIDER: track RT and RI simultaneously so lib is useful for GC and LC?
                                rt = GetRetentionTime(match.Groups[1].Value, true); 
                                isGC = true;
                                continue;
                            }
                        }

                        if (!isPeptide)
                        {
                            if (formula == null)
                            {
                                match = REGEX_FORMULA.Match(line);
                                if (match.Success)
                                {
                                    formula = match.Groups[1].Value;
                                    if (string.Equals(MZVAULT_FORMULA_UNKNOWN, formula, StringComparison.OrdinalIgnoreCase)) // As in mzVault output
                                    {
                                        formula = null;
                                    }
                                    continue;
                                }
                            }
                            if (inChiKey == null)
                            {
                                match = REGEX_INCHIKEY.Match(line);
                                if (match.Success)
                                {
                                    inChiKey = match.Groups[1].Value;
                                    continue;
                                }
                            }
                            if (inChi == null)
                            {
                                match = REGEX_INCHI.Match(line);
                                if (match.Success)
                                {
                                    otherKeys.Add(MoleculeAccessionNumbers.TagInChI, inChi = match.Groups[1].Value);
                                    continue;
                                }
                            }
                            if (CAS == null)
                            {
                                match = REGEX_CAS.Match(line);
                                if (match.Success)
                                {
                                    otherKeys.Add(MoleculeAccessionNumbers.TagCAS, CAS = match.Groups[1].Value);
                                    continue;
                                }
                            }
                            if (KEGG == null)
                            {
                                match = REGEX_KEGG.Match(line);
                                if (match.Success)
                                {
                                    otherKeys.Add(MoleculeAccessionNumbers.TagKEGG, KEGG = match.Groups[1].Value);
                                    continue;
                                }
                            }
                            if (SMILES == null)
                            {
                                match = REGEX_SMILES.Match(line);
                                if (match.Success)
                                {
                                    otherKeys.Add(MoleculeAccessionNumbers.TagSMILES, SMILES = match.Groups[1].Value);
                                    continue;
                                }
                            }
                            if (adduct.IsEmpty)
                            {
                                match = REGEX_ADDUCT.Match(line);
                                if (match.Success)
                                {
                                    // We've seen strange adducts for MS3 data like "[109.1]+" - just preplaced over these
                                    if (!Adduct.TryParse(match.Groups[1].Value, out adduct))
                                        adduct = Adduct.EMPTY;
                                    continue;
                                }
                            }
                            if (!precursorMz.HasValue)
                            {
                                match = REGEX_PRECURSORMZ.Match(line);
                                if (match.Success)
                                {
                                    try
                                    {
                                        precursorMz = double.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
                                    }
                                    catch
                                    {
                                        ThrowIOException(lineCount, string.Format(Resources.NistLibraryBase_CreateCache_Could_not_read_the_precursor_m_z_value___0__ , line) );
                                    }
                                    continue;
                                }
                            }
                            if (!isPositive.HasValue)
                            {
                                match = REGEX_IONMODE.Match(line);
                                if (match.Success)
                                {
                                    if (string.Equals(@"positive", match.Groups[1].Value))
                                        isPositive = true;
                                    else if (string.Equals(@"negative", match.Groups[1].Value))
                                        isPositive = false;
                                    continue;
                                }
                            }
                        }

                        // For peptides (and some molecules), a lot of useful info is jammed into the COMMENT line and must be further picked apart
                        if (line.StartsWith(COMMENT, StringComparison.InvariantCultureIgnoreCase)) // Case insensitive
                        {
                            if (isPeptide)
                            {
                                match = REGEX_MODS.Match(line);
                                if (match.Success)
                                    sequence = Modify(sequence, match.Groups[1].Value);

                                if (!copies.HasValue)
                                {
                                    match = REGEX_SAMPLE.Match(line);
                                    if (match.Success)
                                        copies = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
                                }
                            }

                            if (!tfRatio.HasValue)
                            {
                                match = REGEX_TF_RATIO.Match(line);
                                if (match.Success)
                                    tfRatio = float.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
                            }

                            if (!rt.HasValue)
                            {
                                match = REGEX_RT.Match(line);
                                if (match.Success)
                                    rt = GetRetentionTime(match.Groups[1].Value, false);
                                else
                                {
                                    match = REGEX_RTINSECONDS.Match(line);
                                    if (match.Success)
                                        rt = GetRetentionTime(match.Groups[1].Value, false);
                                }
                            }

                            if (!irt.HasValue)
                            {
                                match = REGEX_IRT.Match(line);
                                if (match.Success)
                                    irt = GetRetentionTime(match.Groups[1].Value, false);
                            }
                        }

                        match = REGEX_NUM_PEAKS.Match(line);
                        if (match.Success)
                        {
                            numPeaksDeclared = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
                            break; // This marks the end of an entry
                        }

                        if (line.StartsWith(@"_EOF_", StringComparison.InvariantCultureIgnoreCase)) // Case insensitive
                            ThrowIOException(lineCount, Resources.NistLibraryBase_CreateCache_Unexpected_end_of_file);
                        else if (line.StartsWith(NAME, StringComparison.InvariantCultureIgnoreCase)) // Case insensitive
                            break;

                        if (line.StartsWith(MZVAULT_POSITIVE_SCAN_INIDCATOR))
                        {
                            isPositive = true;
                            isMzVault = true;
                        }
                        else if (line.StartsWith(MZVAULT_NEGATIVE_SCAN_INIDCATOR))
                        {
                            isPositive = false;
                            isMzVault = true;
                        }
                        if (isMzVault)
                        {
                            // mzVault uses a wider tolerance than most in m/z matching for precursor identification
                            mzMatchTolerance = 10.0 * DEFAULT_MZ_MATCH_TOLERANCE;
                        }
                    } // End parser loop

                    if (formula != null)
                    {
                        // Watch for strange formula specification as seen in MoNA
                        if (formula.StartsWith(@"["))
                        {
                            // In MoNA LipidBlast we've seen "[C11H22NO4]+" replacedociated with adduct [M]+
                            formula = formula.Substring(1).Split(']')[0];
                        }
                        // In MoNA Fiehn-HILIC we see "C7H9N2O+" replacedociated with adduct [M]+ or "C7H9N2O-" with [M]-
                        else
                        {
                            formula = formula.Split('+', '-')[0];
                        }
                    }

                    // Try to infer adduct if none given
                    if (charge == 0 && adduct.IsEmpty && precursorMz.HasValue && ! string.IsNullOrEmpty(formula))
                    {
                        var formulaIn = formula;
                        charge = SmallMoleculeTransitionListReader.ValidateFormulaWithMzAndAdduct(mzMatchTolerance, true,
                            ref formulaIn, ref adduct, new TypedMreplaced(precursorMz.Value, MreplacedType.Monoisotopic), null, isPositive, true, out _, out _, out _) ?? 0;
                        if (!Equals(formula, formulaIn))
                        {
                            // We would not expect to adjust the formula in a library import
                            charge = 0;
                            adduct = Adduct.EMPTY;
                        }
                    }

                    if (isGC && adduct.IsEmpty)
                    {
                        // GCMS is generally EI 
                        adduct = Adduct.M_PLUS;
                    }

                    if (charge == 0 && adduct.IsEmpty)
                        continue; // In the end, couldn't understand this as a peptide nor as a small molecule - ignore. CONSIDER(bspratt): throw an error? Historical behavior is to be silent.

                    if (numPeaksDeclared == 0)
                        ThrowIOException(lineCount, string.Format(Resources.NistLibraryBase_CreateCache_No_peaks_found_for_peptide__0__, sequence));

                    double totalIntensity = 0;
                    var annotations = isPeptide ? null : new List<List<SpectrumPeakAnnotation>>(); // List of lists, as each peak may have multiple annotations
                    int mzBytes = sizeof(float)*numPeaksDeclared;
                    byte[] peaks = new byte[mzBytes*2];
                    int numNonZeroPeaks = 0;
                    for (var i = 0; i < numPeaksDeclared; i++)
                    {
                        var linePeaks = reader.ReadLine();
                        if (linePeaks == null)
                        {
                            ThrowIOException(lineCount, string.Format(Resources.NistLibraryBase_CreateCache_Unexpected_end_of_file_in_peaks_for__0__, sequence));
                            break;  // ReSharper
                        }
                        lineCount++;
                        readChars += linePeaks.Length;
                        IEnumerable<string> lines = null;

                        // Parse out mreplaced and intensity as quickly as possible, since
                        // this will be the most repeated parsing code.
                        var sep = TextUtil.SEPARATOR_TSV; 
                        int iSeperator1 = linePeaks.IndexOf(sep); 
                        if (iSeperator1 == -1) // Using space instead of tab, maybe?
                        {
                            sep = ' '; 
                            iSeperator1 = linePeaks.IndexOf(sep); 
                            var iColon = linePeaks.IndexOf(':');
                            if (iColon > -1 && iColon < iSeperator1)
                            {
                                // Looks like a Golm GMD file e.g. "70:10 76:35 77:1000 78:110 79:42 \n80:4 81:7 86:6 87:5 88:21 " etc
                                sep = ':';
                                lines = linePeaks.Split(' ');
                                iSeperator1 = linePeaks.IndexOf(sep);
                            }
                        }

                        if (lines == null)
                            lines = new[] {linePeaks};

                        foreach (var linePeak in lines)
                        {
                            if (string.IsNullOrEmpty(linePeak))
                            {
                                continue;
                            }
                            if (iSeperator1 < 0)
                            {
                                iSeperator1 = linePeak.IndexOf(sep);
                                i++;
                            }

                            int iSeperator2 = (iSeperator1 == -1 ? -1 : linePeak.IndexOf(sep, iSeperator1 + 1)); 
                            if (iSeperator2 == -1)
                            {
                                if (iSeperator1 != -1)
                                {
                                    iSeperator2 = linePeak.Length; // Some entries don't have annotation columns
                                }
                                else
                                {
                                    ThrowIoExceptionInvalidPeakFormat(lineCount, i, sequence);
                                }
                            }
                            string mzField = linePeak.Substring(0, iSeperator1++);
                            string intensityField = linePeak.Substring(iSeperator1, iSeperator2 - iSeperator1);

                            if (!TryParseFloatUncertainCulture(mzField, out var mz))
                            {
                                ThrowIoExceptionInvalidPeakFormat(lineCount, i, sequence);
                            }
                            if (!TryParseFloatUncertainCulture(intensityField, out var intensity))
                            {
                                ThrowIoExceptionInvalidPeakFormat(lineCount, i, sequence);
                            }
                            if (intensity != 0)
                            {
                                var offset = numNonZeroPeaks * 4;
                                Array.Copy(BitConverter.GetBytes(mz), 0, peaks, offset, 4);
                                Array.Copy(BitConverter.GetBytes(intensity), 0, peaks, mzBytes + offset, 4);
                                numNonZeroPeaks++;
                                totalIntensity += intensity;
                                if (!isPeptide)
                                {
                                    ParseFragmentAnnotation(iSeperator2, annotations, i, linePeak, adduct, charge, mz);
                                }
                            }

                            iSeperator1 = -1; // Next line, if any
                        }
                    }

                    if (numNonZeroPeaks > ushort.MaxValue)
                        ThrowIOException(lineCount, string.Format(Resources.NistLibraryBase_CreateCache_Peak_count_for_MS_MS_spectrum_excedes_maximum__0__, ushort.MaxValue));

                    if (numNonZeroPeaks < numPeaksDeclared)
                    {
                        // Move the intensities down to where the mzs actually stopped, then trim the excess
                        Array.Copy(peaks, sizeof(float) * numPeaksDeclared, peaks, sizeof(float) * numNonZeroPeaks, sizeof(float) * numNonZeroPeaks);
                        Array.Resize(ref peaks, sizeof(float) * numNonZeroPeaks * 2);
                    }


                    // Peak list compression turns out to have a 4x impact on time to
                    // create the cache.  Using zero below turns it off, or 1 to turn
                    // it on, and take the performance hit for 40% less disk use, though
                    // because the text library files are so large, this difference
                    // represents only 5% of the cost of having the library on disk.
                    byte[] peaksCompressed = peaks.Compress(0);
                    int lenCompressed = peaksCompressed.Length;
                    long location = outStream.Position;
                    outStream.Write(peaksCompressed, 0, lenCompressed);
                    int lenAnnotations = 0;
                    if (annotations != null && annotations.Any(a => a != null && !a.All(SpectrumPeakAnnotation.IsNullOrEmpty)))
                    {
                        var annotationsTSV = Encoding.UTF8.GetBytes(SpectrumPeakAnnotation.ToCacheFormat(annotations)); 
                        lenAnnotations = annotationsTSV.Length;
                        outStream.Write(annotationsTSV, 0, lenAnnotations);
                    }
                    var key = isPeptide ? new LibKey(sequence, charge) : new LibKey(SmallMoleculeLibraryAttributes.Create(sequence, formula, inChiKey, otherKeys), adduct);
                    var info = new NistSpectrumInfo(key, tfRatio ?? 1000, rt, irt, Convert.ToSingle(totalIntensity),
                        (ushort) (copies ?? 1), (ushort) numNonZeroPeaks, lenCompressed, lenAnnotations, location);
                    if (!isPeptide)
                    {
                        // Keep an eye out for ambiguous keys, probably due to library containing multiple machine types etc
                        if (!knownKeys.Add(key))
                        {
                            ambiguousKeys.Add(key); // Already in knownKeys, note ambiguity
                        }
                    }
                    libraryEntries.Add(info);
                }

                libraryEntries = FilterInvalidLibraryEntries(ref status, libraryEntries);

                long locationHeaders = outStream.Position;
                foreach (var info in libraryEntries)
                {
                    outStream.Write(BitConverter.GetBytes(info.Key.Charge), 0, sizeof (int));
                    outStream.Write(BitConverter.GetBytes(info.TFRatio), 0, sizeof (float));
                    if (info.RT.HasValue)
                    {
                        outStream.Write(BitConverter.GetBytes(true), 0, sizeof(bool));
                        outStream.Write(BitConverter.GetBytes(info.RT.Value), 0, sizeof(double));
                    }
                    else
                    {
                        outStream.Write(BitConverter.GetBytes(false), 0, sizeof(bool));
                    }
                    if (info.iRT.HasValue)
                    {
                        outStream.Write(BitConverter.GetBytes(true), 0, sizeof(bool));
                        outStream.Write(BitConverter.GetBytes(info.iRT.Value), 0, sizeof(double));
                    }
                    else
                    {
                        outStream.Write(BitConverter.GetBytes(false), 0, sizeof(bool));
                    }
                    outStream.Write(BitConverter.GetBytes(info.TotalIntensity), 0, sizeof (float));
                    outStream.Write(BitConverter.GetBytes(info.Copies), 0, sizeof (int));
                    outStream.Write(BitConverter.GetBytes(info.NumPeaks), 0, sizeof (int));
                    outStream.Write(BitConverter.GetBytes(info.CompressedSize), 0, sizeof(int));
                    outStream.Write(BitConverter.GetBytes(info.AnnotationsSize), 0, sizeof(int));
                    outStream.Write(BitConverter.GetBytes(info.Location), 0, sizeof(long));
                    info.Key.Write(outStream);
                }

                outStream.Write(BitConverter.GetBytes(FORMAT_VERSION_CACHE), 0, sizeof(int));
                outStream.Write(BitConverter.GetBytes(libraryEntries.Count), 0, sizeof(int));
                outStream.Write(BitConverter.GetBytes(locationHeaders), 0, sizeof(long));

                
                sm.Finish(outStream);
                fs.Commit();
                sm.SetCache(FilePath, CachePath);
            }

            loader.UpdateProgress(status.Complete());

            //
            // Especially for small molecules, make user aware if imported library contains multiple entries for the same key.
            // This is probably because the library contains entries for different instruments, CE values etc but we don't track that.
            // N.B. we've tolerated this ambiguity for peptides since the beginning, don't change that behavior now
            //
            if (ambiguousKeys.Any() && ambiguousKeys.All(k => k.IsSmallMoleculeKey))
            {
                var pairType = ambiguousKeys.Any(k => k.IsSmallMoleculeKey)
                    ? Resources.NistLibraryBase_CreateCache_molecule_adduct
                    : Resources.NistLibraryBase_CreateCache_peptide_charge;
                warning = string.Format(Resources.NistLibraryBase_CreateCache_,
                    pairType, TextUtil.LineSeparate(ambiguousKeys.Select(k => k.ToString())));
            }

            return true;
        }

19 View Source File : SimpleBSON.cs
License : GNU General Public License v3.0
Project Creator : ramon-mendes

private void encodeBool(MemoryStream ms, bool v) {
			byte []buf = BitConverter.GetBytes (v);
			ms.Write (buf, 0, buf.Length);
		}

See More Examples