System.Convert.ToByte(string, int)

Here are the examples of the csharp api System.Convert.ToByte(string, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

818 Examples 7

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 3xpl01tc0d3r

public static byte[] StringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

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

public static byte[] ConvertHexStringToBytes(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if (hexString.Length % 2 != 0)
            {
                throw new ArgumentException("wrong length of ntlm hash");
            }

            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            {
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }

            return returnBytes;
        }

19 View Source File : Tlv.cs
License : MIT License
Project Creator : 499116344

private static byte[] GetBytes(string hexString)
        {
            return Enumerable
                .Range(0, hexString.Length)
                .Where(x => x % 2 == 0)
                .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
                .ToArray();
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static byte[] HexStringToByteArray(string hexString)
        {
            hexString = hexString.Replace(" ", "").Replace("\n", "");
            if (hexString.Length % 2 != 0)
            {
                hexString += " ";
            }

            var array = new byte[hexString.Length / 2];
            for (var i = 0; i < array.Length; i++)
            {
                array[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }

            return array;
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static List<byte[]> WriteSnippet(TextSnippet snippet, int length)
        {
            // TODO: 富文本支持
            var ret = new List<byte[]>();
            var bw = new BinaryWriter(new MemoryStream());
            switch (snippet.Type)
            {
                case MessageType.Normal:
                {
                    if (length + 6 >= 699) // 数字应该稍大点,但是我不清楚具体是多少
                    {
                        length = 0;
                        ret.Add(new byte[0]);
                    }

                    bw.BaseStream.Position = 6;
                    foreach (var chr in snippet.Content)
                    {
                        var bytes = Encoding.UTF8.GetBytes(chr.ToString());
                        // 705 = 699 + 6个byte: (byte + short + byte + short)
                        if (length + bw.BaseStream.Length + bytes.Length > 705)
                        {
                            var pos = bw.BaseStream.Position;
                            bw.BaseStream.Position = 0;
                            bw.Write(new byte[]
                            {
                                0x01
                            });
                            bw.BeWrite((ushort) (pos - 3)); // 本来是+3和0的,但是提前预留了6个byte给它们,所以变成了-3和-6。下同理。
                            bw.Write(new byte[]
                            {
                                0x01
                            });
                            bw.BeWrite((ushort) (pos - 6));
                            bw.BaseStream.Position = pos;
                            ret.Add(bw.BaseStream.ToBytesArray());
                            bw = new BinaryWriter(new MemoryStream());
                            bw.BaseStream.Position = 6;
                            length = 0;
                        }

                        bw.Write(bytes);
                    }

                    // 在最后一段的开头补充结构 
                    {
                        var pos = bw.BaseStream.Position;
                        bw.BaseStream.Position = 0;
                        bw.Write(new byte[]
                        {
                            0x01
                        });
                        bw.BeWrite((ushort) (pos - 3));
                        bw.Write(new byte[]
                        {
                            0x01
                        });
                        bw.BeWrite((ushort) (pos - 6));
                        bw.BaseStream.Position = pos;
                    }
                    break;
                }
                case MessageType.At:
                    break;
                case MessageType.Emoji:
                {
                    if (length + 12 > 699)
                    {
                        ret.Add(new byte[0]);
                    }

                    var faceIndex = Convert.ToByte(snippet.Content);
                    if (faceIndex > 199)
                    {
                        faceIndex = 0;
                    }

                    bw.Write(new byte[]
                    {
                        0x02,
                        0x00,
                        0x14,
                        0x01,
                        0x00,
                        0x01
                    });
                    bw.Write(faceIndex);
                    bw.Write(new byte[]
                    {
                        0xFF,
                        0x00,
                        0x02,
                        0x14
                    });
                    bw.Write((byte) (faceIndex + 65));
                    bw.Write(new byte[]
                    {
                        0x0B,
                        0x00,
                        0x08,
                        0x00,
                        0x01,
                        0x00,
                        0x04,
                        0x52,
                        0xCC,
                        0x85,
                        0x50
                    });
                    break;
                }
                case MessageType.Picture:
                    break;
                case MessageType.Xml:
                    break;
                case MessageType.Json:
                    break;
                case MessageType.Shake:
                    break;
                case MessageType.Audio:
                    break;
                case MessageType.Video:
                    break;
                case MessageType.ExitGroup:
                    break;
                case MessageType.GetGroupImformation:
                    break;
                case MessageType.AddGroup:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            if (bw.BaseStream.Position != 0)
            {
                ret.Add(bw.BaseStream.ToBytesArray());
            }

            return ret;
        }

19 View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063

private byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0) hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
            return returnBytes;
        }

19 View Source File : SecureExtensions.cs
License : MIT License
Project Creator : Accelerider

public static string DecryptByRijndael(this string text, byte[] key = null, byte[] iv = null)
        {
            if (string.IsNullOrEmpty(text)) return string.Empty;

            string plainText;
            using (var rijndaelAlgorithm = new RijndaelManaged())
            {
                rijndaelAlgorithm.Key = key ?? DefaultKey;
                rijndaelAlgorithm.IV = iv ?? DefaultIv;
                var decryptor = rijndaelAlgorithm.CreateDecryptor(rijndaelAlgorithm.Key, rijndaelAlgorithm.IV);
                var cipherByte = new byte[text.Length / 2];
                for (int i = 0; i < cipherByte.Length; i++)
                {
                    cipherByte[i] = Convert.ToByte(text.Substring(i * 2, 2), 16);
                }
                try
                {
                    using (var msDecrypt = new MemoryStream(cipherByte))
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    using (var srDecrypt = new StreamReader(csDecrypt))
                    {
                        plainText = srDecrypt.ReadToEnd();
                    }
                }
                catch (CryptographicException)
                {
                    return text;
                }
            }
            return plainText;
        }

19 View Source File : HMACValidator.cs
License : MIT License
Project Creator : Adyen

private byte[] PackH(string hex)
        {
            if ((hex.Length % 2) == 1)
            {
                hex += '0';
            }

            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < hex.Length; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            }

            return bytes;
        }

19 View Source File : ByteArrayHelper.cs
License : MIT License
Project Creator : AElfProject

public static byte[] HexStringToByteArray(string hex)
        {
            if (hex.Length >= 2 && hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X'))
                hex = hex.Substring(2);
            int numberChars = hex.Length;
            byte[] bytes = new byte[numberChars / 2];

            for (int i = 0; i < numberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);

            return bytes;
        }

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

private byte[] ConvertPattern(String pattern)
        {
            List<byte> convertertedArray = new List<byte>();
            foreach (String each in pattern.Split(' '))
            {
                if (each == "??") { convertertedArray.Add(Convert.ToByte("0", 16)); }
                else{ convertertedArray.Add(Convert.ToByte(each,16)); }
            }
            return convertertedArray.ToArray();

        }

19 View Source File : Stream.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

[ContextMethod("Записать", "Write")]
        public void Write(ClArrayList p1, int p2, int p3)
        {
            ArrayList ArrayList1 = p1.Base_obj;
            int Count1 = ArrayList1.Count;
            object[] objects = new object[Count1];
            for (int i = 0; i < Count1; i++)
            {
                objects[i] = System.Convert.ToByte(ArrayList1[i]);
            }
            Base_obj.Write(objects, p2, p3);
        }

19 View Source File : Bitmap.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy

public void SetBytes(osf.BitmapData p1, osf.ArrayList p2)
        {
            int num = p2.M_ArrayList.Count;
            byte[] Bytes1 = new byte[num];
            for (int i = 0; i < num; i++)
            {
                Bytes1[i] = System.Convert.ToByte(p2.M_ArrayList[i].ToString());
            }
            System.Runtime.InteropServices.Marshal.Copy(Bytes1, 0, p1.M_BitmapData.Scan0, num);
        }

19 View Source File : BinaryConverter.cs
License : MIT License
Project Creator : akaskela

private byte[] ReadByteArray(JsonReader reader)
        {
            List<byte> byteList = new List<byte>();

            while (reader.Read())
            {
                switch (reader.TokenType)
                {
                    case JsonToken.Integer:
                        byteList.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
                        break;
                    case JsonToken.EndArray:
                        return byteList.ToArray();
                    case JsonToken.Comment:
                        // skip
                        break;
                    default:
                        throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
                }
            }

            throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
        }

19 View Source File : KrakenXChannel.cs
License : GNU General Public License v3.0
Project Creator : akmadian

public byte[] BuildColorBytes(Color Color)
        {
            List<byte> outBytes = new List<byte>();
            if (_IsActive)
            {
                outBytes.Add(Convert.ToByte(Color.G));
                outBytes.Add(Convert.ToByte(Color.R));
                outBytes.Add(Convert.ToByte(Color.B));

                for (int i = 0; i < _Leds.Length; i++)
                {
                    if (!_Leds[i])
                    {
                        outBytes.Add(0x00);
                        outBytes.Add(0x00);
                        outBytes.Add(0x00);
                    }
                    else
                    {
                        outBytes.Add(Convert.ToByte(Color.R));
                        outBytes.Add(Convert.ToByte(Color.G));
                        outBytes.Add(Convert.ToByte(Color.B));
                    }
                }

                int numToPad = 0x41 - 5 - (9 * 3);

                outBytes = outBytes.PadList(numToPad);

                return outBytes.ToArray();
            } else
            {
                int numToPad = 0x41 - 5;
                outBytes = outBytes.PadList(numToPad);
                return outBytes.ToArray();
            }
        }

19 View Source File : AES.cs
License : MIT License
Project Creator : albyho

private static Byte[] ByteArrayFromHexString(string hexString)
        {
            if (hexString.IsNullOrWhiteSpace() || hexString.Length % 2 != 0)
            {
                return new Byte[0];
            }
            var buffer = new Byte[hexString.Length / 2];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            return buffer;
        }

19 View Source File : DES.cs
License : MIT License
Project Creator : albyho

public static string DecryptFromHexToString(string decryptString, string key = null)
        {
            var decryptBuffer = new Byte[decryptString.Length / 2];
            for (int i = 0; i < decryptBuffer.Length; i++)
            {
                decryptBuffer[i] = Convert.ToByte(decryptString.Substring(i * 2, 2), 16);
            }
            return Encoding.UTF8.GetString(DecryptFromByteArrayToByteArray(decryptBuffer, key)).Replace("\0", "");

        }

19 View Source File : Hexadecimal.cs
License : MIT License
Project Creator : alecgn

public static byte[] ToByteArray(string hexString)
        {
            if (string.IsNullOrWhiteSpace(hexString))
            {
                return null;
            }

            if (hexString.Length % 2 != 0)
            {
                throw new ArgumentException(MessageStrings.Common_IncorrectHexadecimalString, nameof(hexString));
            }

            var byteArray = new byte[hexString.Length / 2];
            var i = 0;

            foreach (var hexVal in ChunkHexString(hexString))
            {
                byteArray[i] = Convert.ToByte(hexVal, 16);
                i++;
            }

            return byteArray;
        }

19 View Source File : HexStringArray.cs
License : MIT License
Project Creator : AlexGyver

public static byte Read(string s, ushort address) {
      string[] lines = s.Split(new[] { '\r', '\n' }, 
        StringSplitOptions.RemoveEmptyEntries);

      foreach (string line in lines) {
        string[] array = line.Split(new[] { ' ', '\t' }, 
          StringSplitOptions.RemoveEmptyEntries);
        if (array.Length == 0)
          continue; 
        if (Convert.ToInt32(array[0], 16) == (address & 0xFFF0)) 
          return Convert.ToByte(array[(address & 0x0F) + 1], 16);
      }

      throw new ArgumentException();
    }

19 View Source File : Eui64Record.cs
License : Apache License 2.0
Project Creator : alexreinert

internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
		{
			if (stringRepresentation.Length != 1)
				throw new NotSupportedException();

			Address = stringRepresentation[0].Split('-').Select(x => Convert.ToByte(x, 16)).ToArray();

			if (Address.Length != 8)
				throw new NotSupportedException();
		}

19 View Source File : Eui48Record.cs
License : Apache License 2.0
Project Creator : alexreinert

internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
		{
			if (stringRepresentation.Length != 1)
				throw new NotSupportedException();

			Address = stringRepresentation[0].Split('-').Select(x => Convert.ToByte(x, 16)).ToArray();

			if (Address.Length != 6)
				throw new NotSupportedException();
		}

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

public static byte[] ToByteArray(this string value)
        {
            value.CannotBeNull();

            return Enumerable.Range(0, value.Length / 2).Select(x => Convert.ToByte(value.Substring(x * 2, 2), 16)).ToArray();
        }

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

public static byte[] HexToByteArray(this string hex)
        {
            var bytes = Enumerable.Range(0, hex.Length / 2)
                    .Select(x => Convert.ToByte(hex.Substring(x * 2, 2), 16))
                    .ToArray();

            return bytes;
        }

19 View Source File : CryptoBytes.cs
License : MIT License
Project Creator : allartprotocol

public static byte[] FromHexString(string hexString)
        {
            if (hexString == null)
                return null;
            if (hexString.Length % 2 != 0)
                throw new FormatException("The hex string is invalid because it has an odd length");
            var result = new byte[hexString.Length / 2];
            for (int i = 0; i < result.Length; i++)
                result[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return result;
        }

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

private static async Task<int> RunClientAsync(ILogger logger, CancellationToken cancellationToken)
		{
			Console.Write("Connection Type [1] TCP, [2] RS485: ");
			int cType = Convert.ToInt32(Console.ReadLine().Trim());

			IModbusClient client = null;
			try
			{
				switch (cType)
				{
					case 1:
						{
							Console.Write("Hostname: ");
							string host = Console.ReadLine().Trim();
							Console.Write("Port: ");
							int port = Convert.ToInt32(Console.ReadLine().Trim());

							client = new TcpClient(host, port, logger);
						}
						break;
					case 2:
						{
							Console.Write("Interface: ");
							string port = Console.ReadLine().Trim();

							Console.Write("Baud: ");
							int baud = Convert.ToInt32(Console.ReadLine().Trim());

							Console.Write("Stop-Bits [0|1|2|3=1.5]: ");
							int stopBits = Convert.ToInt32(Console.ReadLine().Trim());

							Console.Write("Parity [0] None [1] Odd [2] Even [3] Mark [4] Space: ");
							int parity = Convert.ToInt32(Console.ReadLine().Trim());

							Console.Write("Handshake [0] None [1] X-On/Off [2] RTS [3] RTS+X-On/Off: ");
							int handshake = Convert.ToInt32(Console.ReadLine().Trim());

							Console.Write("Timeout (ms): ");
							int timeout = Convert.ToInt32(Console.ReadLine().Trim());

							Console.Write("Set Driver to RS485 [0] No [1] Yes: ");
							int setDriver = Convert.ToInt32(Console.ReadLine().Trim());

							client = new SerialClient(port)
							{
								BaudRate = (BaudRate)baud,
								DataBits = 8,
								StopBits = (StopBits)stopBits,
								Parity = (Parity)parity,
								Handshake = (Handshake)handshake,
								SendTimeout = TimeSpan.FromMilliseconds(timeout),
								ReceiveTimeout = TimeSpan.FromMilliseconds(timeout)
							};

							if (setDriver == 1)
							{
								((SerialClient)client).DriverEnableRS485 = true;
							}
						}
						break;
					default:
						Console.Error.WriteLine($"Unknown type: {cType}");
						return 1;
				}

				await Task.WhenAny(client.Connect(), Task.Delay(Timeout.Infinite, cancellationToken));
				if (cancellationToken.IsCancellationRequested)
					return 0;

				while (!cancellationToken.IsCancellationRequested)
				{
					Console.Write("Device ID: ");
					byte id = Convert.ToByte(Console.ReadLine().Trim());

					Console.Write("Function [1] Read Register, [2] Device Info, [9] Write Register : ");
					int fn = Convert.ToInt32(Console.ReadLine().Trim());

					switch (fn)
					{
						case 1:
							{
								ushort address = 0;
								ushort count = 0;
								string type = "";

								Console.WriteLine();
								Console.Write("Address : ");
								address = Convert.ToUInt16(Console.ReadLine().Trim());
								Console.Write("DataType: ");
								type = Console.ReadLine().Trim();
								if (type == "string")
								{
									Console.Write("Register Count: ");
									count = Convert.ToUInt16(Console.ReadLine().Trim());
								}

								Console.WriteLine();
								Console.Write("Run as loop? [y/N]: ");
								string loop = Console.ReadLine().Trim().ToLower();
								int interval = 0;
								if (yesList.Contains(loop))
								{
									Console.Write("Loop interval (milliseconds): ");
									interval = Convert.ToInt32(Console.ReadLine().Trim());
								}

								Console.WriteLine();
								do
								{
									try
									{
										Console.Write("Result  : ");
										List<Register> result = null;
										switch (type.Trim().ToLower())
										{
											case "byte":
												result = await client.ReadHoldingRegisters(id, address, 1);
												Console.WriteLine(result?.First().GetByte());
												break;
											case "ushort":
												result = await client.ReadHoldingRegisters(id, address, 1);
												Console.WriteLine(result?.First().GetUInt16());
												break;
											case "uint":
												result = await client.ReadHoldingRegisters(id, address, 2);
												Console.WriteLine(result?.GetUInt32());
												break;
											case "ulong":
												result = await client.ReadHoldingRegisters(id, address, 4);
												Console.WriteLine(result?.GetUInt64());
												break;
											case "sbyte":
												result = await client.ReadHoldingRegisters(id, address, 1);
												Console.WriteLine(result?.First().GetSByte());
												break;
											case "short":
												result = await client.ReadHoldingRegisters(id, address, 1);
												Console.WriteLine(result?.First().GetInt16());
												break;
											case "int":
												result = await client.ReadHoldingRegisters(id, address, 2);
												Console.WriteLine(result?.GetInt32());
												break;
											case "long":
												result = await client.ReadHoldingRegisters(id, address, 4);
												Console.WriteLine(result?.GetInt64());
												break;
											case "float":
												result = await client.ReadHoldingRegisters(id, address, 2);
												Console.WriteLine(result?.GetSingle());
												break;
											case "double":
												result = await client.ReadHoldingRegisters(id, address, 4);
												Console.WriteLine(result?.GetDouble());
												break;
											case "string":
												result = await client.ReadHoldingRegisters(id, address, count);
												Console.WriteLine();
												Console.WriteLine("UTF8:             " + result?.GetString(count));
												Console.WriteLine("Unicode:          " + result?.GetString(count, 0, Encoding.Unicode));
												Console.WriteLine("BigEndianUnicode: " + result?.GetString(count, 0, Encoding.BigEndianUnicode));
												break;
											default:
												Console.Write("DataType unknown");
												break;
										}
									}
									catch
									{ }
									await Task.Delay(TimeSpan.FromMilliseconds(interval), cancellationToken);
								}
								while (interval > 0 && !cancellationToken.IsCancellationRequested);
							}
							break;
						case 2:
							{
								Console.Write("[1] Basic, [2] Regular, [3] Extended: ");
								int cat = Convert.ToInt32(Console.ReadLine().Trim());

								Dictionary<DeviceIDObject, string> info = null;
								switch (cat)
								{
									case 1:
										info = await client.ReadDeviceInformation(id, DeviceIDCategory.Basic);
										break;
									case 2:
										info = await client.ReadDeviceInformation(id, DeviceIDCategory.Regular);
										break;
									case 3:
										info = await client.ReadDeviceInformation(id, DeviceIDCategory.Extended);
										break;
								}
								if (info != null)
								{
									foreach (var kvp in info)
									{
										Console.WriteLine($"{kvp.Key}: {kvp.Value}");
									}
								}
							}
							break;
						case 9:
							{
								Console.Write("Address: ");
								ushort address = Convert.ToUInt16(Console.ReadLine().Trim());

								Console.Write("Bytes (HEX): ");
								string byteStr = Console.ReadLine().Trim();
								byteStr = byteStr.Replace(" ", "").ToLower();

								byte[] bytes = Enumerable.Range(0, byteStr.Length)
									.Where(i => i % 2 == 0)
									.Select(i => Convert.ToByte(byteStr.Substring(i, 2), 16))
									.ToArray();

								var registers = Enumerable.Range(0, bytes.Length)
									.Where(i => i % 2 == 0)
									.Select(i =>
									{
										return new Register
										{
											Type = ModbusObjectType.HoldingRegister,
											Address = address++,
											HiByte = bytes[i],
											LoByte = bytes[i + 1]
										};
									})
									.ToList();

								if (!await client.WriteRegisters(id, registers))
									throw new Exception($"Writing '{byteStr}' to address {address} failed");
							}
							break;
					}

					Console.Write("New Request? [y/N]: ");
					string again = Console.ReadLine().Trim().ToLower();
					if (!yesList.Contains(again))
						return 0;
				}

				return 0;
			}
			catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
			{
				return 0;
			}
			finally
			{
				Console.WriteLine("Disposing");
				client?.Dispose();
				Console.WriteLine("Disposed");
			}
		}

19 View Source File : Opcode_Disassembler.cs
License : MIT License
Project Creator : Andy53

private static byte[] HexStringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => System.Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

19 View Source File : CCBPayUtil.cs
License : Apache License 2.0
Project Creator : anjoy8

private byte[] hexStrToBytes(string s)
		{
			s = s.Replace(" ", "");
			if (s.Length % 2 != 0)
			{
				s += " ";
			}
			byte[] array = new byte[s.Length / 2];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);
			}
			return array;
		}

19 View Source File : helpers.cs
License : Apache License 2.0
Project Creator : AntonioDePau

public static byte[] ToBytes(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

19 View Source File : AmqpMessageIdHelper.cs
License : Apache License 2.0
Project Creator : apache

private static byte[] ConvertHexStringToBinary(string hex, string originalId)
        {
            // As each byte needs two characters in the hex encoding, the string must be an even length.
            if (hex == null || hex.Length % 2 != 0)
            {
                throw new NMSException("Invalid Binary MessageId " + originalId);
            }

            int size = hex.Length / 2;
            int index = 0;
            byte[] result = new byte[size];
            for (int i = 0; i < result.Length; i++)
            {
                char upper = hex[index];
                index++;
                char lower = hex[index];
                index++;
                char[] subchars = {upper, lower};
                string substring = new string(subchars);
                result[i] = Convert.ToByte(substring, 16);
            }

            return result;
        }

19 View Source File : EntitiesConverter.cs
License : MIT License
Project Creator : apdevelop

public static int GetArgbColorFromString(string rgbHexColor, bool isTransparent)
        {
            if (rgbHexColor.StartsWith("0x"))
            {
                rgbHexColor = rgbHexColor.Substring(2);
            }

            return BitConverter.ToInt32(
                new[]
                {
                    Convert.ToByte(rgbHexColor.Substring(4, 2), 16),
                    Convert.ToByte(rgbHexColor.Substring(2, 2), 16),
                    Convert.ToByte(rgbHexColor.Substring(0, 2), 16),
                    (byte)(isTransparent ? 0x00 : 0xFF),
                },
            0);
        }

19 View Source File : QRParser.cs
License : MIT License
Project Creator : architdate

public byte[] ToByteArray(string toTransform)
        {
            return Enumerable
                .Range(0, toTransform.Length / 2)
                .Select(i => Convert.ToByte(toTransform.Substring(i * 2, 2), 16))
                .ToArray();
        }

19 View Source File : Decoder.cs
License : MIT License
Project Creator : architdate

public static byte[] StringToByteArray(string hex)
        {
            int NumberChars = hex.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            return bytes;
        }

19 View Source File : QRParser.cs
License : MIT License
Project Creator : architdate

private static byte[] ToByteArray(string toTransform)
        {
            return Enumerable
                .Range(0, toTransform.Length / 2)
                .Select(i => Convert.ToByte(toTransform.Substring(i * 2, 2), 16))
                .ToArray();
        }

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

public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.StartArray)
            {
                var byteList = new List<byte>();

                while (reader.Read())
                {
                    switch (reader.TokenType)
                    {
                        case JsonToken.Integer:
                            byteList.Add(Convert.ToByte(reader.Value));
                            break;
                        case JsonToken.EndArray:
                            return byteList.ToArray();
                        case JsonToken.Comment:
                            // skip
                            break;
                        default:
                            throw new Exception(
                            string.Format(
                                "Unexpected token when reading bytes: {0}",
                                reader.TokenType));
                    }
                }

                throw new Exception("Unexpected end when reading bytes.");
            }
            else
            {
                throw new Exception(
                    string.Format(
                        "Unexpected token parsing binary. "
                        + "Expected StartArray, got {0}.",
                        reader.TokenType));
            }
        }

19 View Source File : BaseLayer.cs
License : Apache License 2.0
Project Creator : ascora

private int ApplyMasks(BitmapCanvas canvas, Matrix3X3 matrix, Mask.MaskMode maskMode)
        {
            Paint paint;
            switch (maskMode)
            {
                case Mask.MaskMode.MaskModeSubtract:
                    paint = _subtractMaskPaint;
                    break;
                case Mask.MaskMode.MaskModeIntersect:
                    goto case Mask.MaskMode.MaskModeAdd;
                case Mask.MaskMode.MaskModeAdd:
                default:
                    // As a hack, we treat all non-subtract masks like add masks. This is not corRectangleF but it's 
                    // better than nothing.
                    paint = _addMaskPaint;
                    break;
            }

            var size = _mask.Masks.Count;

            var hasMask = false;
            for (int i = 0; i < size; i++)
            {
                if (_mask.Masks[i].GetMaskMode() == maskMode)
                {
                    hasMask = true;
                    break;
                }
            }
            if (!hasMask)
            {
                return 0;
            }
            LottieLog.BeginSection("Layer.DrawMask");
            LottieLog.BeginSection("Layer.SaveLayer");
            canvas.SaveLayer(Rect, paint, SaveFlags);
            LottieLog.EndSection("Layer.SaveLayer");
            ClearCanvas(canvas);

            for (var i = 0; i < size; i++)
            {
                var mask = _mask.Masks[i];
                if (mask.GetMaskMode() != maskMode)
                {
                    continue;
                }
                var maskAnimation = _mask.MaskAnimations[i];
                var maskPath = maskAnimation.Value;
                _path.Set(maskPath);
                _path.Transform(matrix);
                var opacityAnimation = _mask.OpacityAnimations[i];
                var alpha = _contentPaint.Alpha;
                _contentPaint.Alpha = Convert.ToByte(opacityAnimation.Value.Value * 2.55f);
                canvas.DrawPath(_path, _contentPaint, true);
                _contentPaint.Alpha = alpha;
            }
            LottieLog.BeginSection("Layer.RestoreLayer");
            canvas.Restore();
            LottieLog.EndSection("Layer.RestoreLayer");
            LottieLog.EndSection("Layer.DrawMask");

            return size;
        }

19 View Source File : EncodingUtilities.cs
License : Apache License 2.0
Project Creator : aspnet

public static byte[] FromHex(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return new byte[0];
            }

            byte[] data = null;
            try
            {
                data = new byte[content.Length / 2];
                var input = 0;
                for (var output = 0; output < data.Length; output++)
                {
                    data[output] = Convert.ToByte(new string(new char[2] { content[input++], content[input++] }), 16);
                }

                if (input != content.Length)
                {
                    data = null;
                }
            }
            catch
            {
                data = null;
            }

            if (data == null)
            {
                var message = string.Format(CultureInfo.CurrentCulture, CommonResources.EncodingUtils_InvalidHexValue, content);
                throw new InvalidOperationException(message);
            }

            return data;
        }

19 View Source File : UAGUtils.cs
License : MIT License
Project Creator : atenfyr

public static byte[] ConvertStringToByteArray(this string val)
        {
            if (val == null) return new byte[0];
            string[] rawStringArr = val.Split(' ');
            byte[] byteArr = new byte[rawStringArr.Length];
            for (int i = 0; i < rawStringArr.Length; i++) byteArr[i] = Convert.ToByte(rawStringArr[i], 16);
            return byteArr;
        }

19 View Source File : Forge.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

public static string ForgeInt(int value)
        {
            var binary = Convert.ToString(Math.Abs(value), 2);

            int pad = 6;
            if ((binary.Length - 6) % 7 == 0)
                pad = binary.Length;
            else if (binary.Length > 6)
                pad = binary.Length + 7 - (binary.Length - 6) % 7;

            binary = binary.PadLeft(pad, '0');

            var septets = new List<string>();

            for (int i = 0; i <= pad / 7; i++)
                septets.Add(binary.Substring(7 * i, Math.Min(7, pad - 7 * i)));

            septets.Reverse();

            septets[0] = (value >= 0 ? "0" : "1") + septets[0];

            string res = "";

            for (int i = 0; i < septets.Count; i++)
            {
                var prefix = i == septets.Count - 1
                    ? "0"
                    : "1";

                res += Convert.ToByte(prefix + septets[i], 2).ToString("X2");
            }

            return res;
        }

19 View Source File : CognitoAuthHelper.cs
License : Apache License 2.0
Project Creator : aws

internal static byte[] StringToByteArray(string hexString)
        {
            if(hexString.Length % 2 != 0)
            {
                throw new ArgumentException("Malformed hexString.", "hexString");
            }

            int stringLen = hexString.Length;
            byte[] bytes = new byte[stringLen / 2];

            for (int i = 0; i < stringLen; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
            }

            return bytes;
        }

19 View Source File : HeightmapTerrainZonePageSource.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d

public override void Initialize(TerrainZone tsm, int tileSize, int pageSize, bool asyncLoading,
                                         TerrainZonePageSourceOptionList optionList)
        {
            // Shutdown to clear any previous data
            Shutdown();

            base.Initialize(tsm, tileSize, pageSize, asyncLoading, optionList);

            // Get source image

            bool imageFound = false;
            this.mIsRaw = false;
            bool rawSizeFound = false;
            bool rawBppFound = false;
            foreach (var opt in optionList)
            {
                string key = opt.Key;
                key = key.Trim();
                if (key.StartsWith("HeightmapImage".ToLower(), StringComparison.InvariantCultureIgnoreCase))
                {
                    this.mSource = opt.Value;
                    imageFound = true;
                    // is it a raw?
                    if (this.mSource.ToLowerInvariant().Trim().EndsWith("raw"))
                    {
                        this.mIsRaw = true;
                    }
                }
                else if (key.StartsWith("Heightmap.raw.size", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.mRawSize = Convert.ToInt32(opt.Value);
                    rawSizeFound = true;
                }
                else if (key.StartsWith("Heightmap.raw.bpp", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.mRawBpp = Convert.ToByte(opt.Value);
                    if (this.mRawBpp < 1 || this.mRawBpp > 2)
                    {
                        throw new AxiomException(
                            "Invalid value for 'Heightmap.raw.bpp', must be 1 or 2. HeightmapTerrainZonePageSource.Initialise");
                    }
                    rawBppFound = true;
                }
                else if (key.StartsWith("Heightmap.flip", StringComparison.InvariantCultureIgnoreCase))
                {
                    this.mFlipTerrainZone = Convert.ToBoolean(opt.Value);
                }
                else
                {
                    LogManager.Instance.Write("Warning: ignoring unknown Heightmap option '" + key + "'");
                }
            }
            if (!imageFound)
            {
                throw new AxiomException("Missing option 'HeightmapImage'. HeightmapTerrainZonePageSource.Initialise");
            }
            if (this.mIsRaw && (!rawSizeFound || !rawBppFound))
            {
                throw new AxiomException(
                    "Options 'Heightmap.raw.size' and 'Heightmap.raw.bpp' must be specified for RAW heightmap sources. HeightmapTerrainZonePageSource.Initialise");
            }
            // Load it!
            LoadHeightmap();
        }

19 View Source File : ObjectValueConversion.cs
License : MIT License
Project Creator : azist

public static byte AsByte(this object val, byte dflt = 0, ConvertErrorHandling handling = ConvertErrorHandling.ReturnDefault)
    {
      try
      {
        if (val == null) return dflt;
        if (val is string)
        {
          var sval = ((string)val).Trim();
          if (sval.StartsWith(RADIX_BIN, StringComparison.InvariantCultureIgnoreCase)) return Convert.ToByte(sval.Substring(2), 2);
          if (sval.StartsWith(RADIX_HEX, StringComparison.InvariantCultureIgnoreCase)) return Convert.ToByte(sval.Substring(2), 16);
        }
        return Convert.ToByte(val, INVARIANT);
      }
      catch
      {
        if (handling != ConvertErrorHandling.ReturnDefault) throw;
        return dflt;
      }
    }

19 View Source File : ObjectValueConversion.cs
License : MIT License
Project Creator : azist

public static byte? AsNullableByte(this object val, byte? dflt = null, ConvertErrorHandling handling = ConvertErrorHandling.ReturnDefault)
    {
      try
      {
        if (val == null) return null;
        if (val is string)
        {
          var sval = ((string)val).Trim();
          if (sval.StartsWith(RADIX_BIN, StringComparison.InvariantCultureIgnoreCase)) return Convert.ToByte(sval.Substring(2), 2);
          if (sval.StartsWith(RADIX_HEX, StringComparison.InvariantCultureIgnoreCase)) return Convert.ToByte(sval.Substring(2), 16);
        }
        return Convert.ToByte(val, INVARIANT);
      }
      catch
      {
        if (handling != ConvertErrorHandling.ReturnDefault) throw;
        return dflt;
      }
    }

19 View Source File : BSONTestForm.cs
License : MIT License
Project Creator : azist

public void WriteSingleObjectId(Stream stream)
    {
      var hex = "507f1f77bcf86cd799439011";
      var data = Enumerable.Range(0, hex.Length)
                   .Where(x => x % 2 == 0)
                   .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                   .ToArray();
      var root = new BSONDoreplacedent();
      var objectId = new BSONObjectID(data);
      root.Set(new BSONObjectIDElement("objectId", objectId));
      root.WriteAsBSON(stream);
    }

19 View Source File : BatchTestBase.cs
License : MIT License
Project Creator : Azure

protected static byte[] HexStringToBytes(string input)
        {
            byte[] bytes = new byte[input.Length / 2];
            for (int i = 0; i < input.Length; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(input.Substring(i, 2), 16);
            }

            return bytes;
        }

19 View Source File : EasyAuthTokenManager.cs
License : MIT License
Project Creator : Azure

protected static byte[] HexStringToByteArray(string hexString)
            {
                byte[] bytes = new byte[hexString.Length / 2];
                for (int i = 0; i < hexString.Length; i += 2)
                {
                    bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
                }

                return bytes;
            }

19 View Source File : ConversionHelper.cs
License : MIT License
Project Creator : Azure

public static byte[] StringToByteArray(string hex)
        {
            if (hex is null) throw new ArgumentNullException(nameof(hex));

            var numberChars = hex.Length;
            var bytes = new byte[numberChars / 2];
            for (var i = 0; i < numberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            return bytes;
        }

19 View Source File : ConversionHelper.cs
License : MIT License
Project Creator : Azure

public static byte[] StringToByteArray(string hex)
        {
            if (hex is null) throw new ArgumentNullException(nameof(hex));
            var NumberChars = hex.Length;
            var bytes = new byte[NumberChars / 2];
            for (var i = 0; i < NumberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            return bytes;
        }

19 View Source File : ConversionHelper.cs
License : MIT License
Project Creator : Azure

public static byte[] StringToByteArray(string hex)
        {
            if (hex is null) throw new ArgumentNullException(nameof(hex));
            var numberChars = hex.Length;
            var bytes = new byte[numberChars / 2];
            for (var i = 0; i < numberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            return bytes;
        }

19 View Source File : DecoderController.cs
License : MIT License
Project Creator : Azure

[HttpGet("{decoder}", Name = "Get")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        public IActionResult Get(string devEUI, string decoder, string fport, string payload)
        {
            // Validate that fport and payload URL parameters are present.
            Validator.ValidateParameters(fport, payload);

            var decoderType = typeof(LoraDecoders);
            var toInvoke = decoderType.GetMethod(decoder, BindingFlags.Static | BindingFlags.NonPublic);

            if (toInvoke != null)
            {
                var decoderResult = (string)toInvoke.Invoke(null, new object[] { devEUI, Convert.FromBase64String(payload), Convert.ToByte(fport, CultureInfo.InvariantCulture) });
                return this.Ok(decoderResult);
            }
            else
            {
                throw new WebException($"Decoder {decoder} not found.");
            }
        }

19 View Source File : ConversionHelper.cs
License : MIT License
Project Creator : Azure

public static byte[] StringToByteArray(string hex)
        {
            int numberChars = hex.Length;

            byte[] bytes = new byte[numberChars >> 1];

            if (numberChars % 2 == 0)
            {
                for (int i = 0; i < numberChars; i += 2)
                    bytes[i >> 1] = Convert.ToByte(hex.Substring(i, 2), 16);
            }

            return bytes;
        }

19 View Source File : TDSClientVersion.cs
License : MIT License
Project Creator : Azure

public bool Unpack(MemoryStream stream)
        {
            this.BuildNumber = BigEndianUtilities.ReadUShort(stream);
            this.Minor = Convert.ToByte(stream.ReadByte());
            this.Major = Convert.ToByte(stream.ReadByte());
            this.SubBuildNumber = BigEndianUtilities.ReadUShort(stream);
           
            return true;
        }

See More Examples