System.Collections.Generic.List.Add(byte)

Here are the examples of the csharp api System.Collections.Generic.List.Add(byte) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1493 Examples 7

19 Source : HijackThread.cs
with MIT License
from Akaion

private static byte[] replacedembleShellcode(CallDescriptor callDescriptor, IntPtr completionFlagBuffer)
        {
            var shellcode = new List<byte>();

            if (callDescriptor.IsWow64Call)
            {
                // pushf

                shellcode.Add(0x9C);

                // pusha

                shellcode.Add(0x60);

                // replacedemble the function parameters

                if (callDescriptor.CallingConvention == CallingConvention.FastCall)
                {
                    Parameterreplacedembler.replacedembleFastCallParameters(callDescriptor, ref shellcode);
                }

                else
                {
                    Parameterreplacedembler.replacedembleStdCallParameters(callDescriptor, ref shellcode);
                }

                // mov eax, functionAddress

                shellcode.Add(0xB8);

                shellcode.AddRange(BitConverter.GetBytes((int) callDescriptor.FunctionAddress));

                // call eax

                shellcode.AddRange(new byte[] {0xFF, 0xD0});

                if (callDescriptor.ReturnAddress != IntPtr.Zero)
                {
                    // mov [returnAddress], eax

                    shellcode.Add(0xA3);

                    shellcode.AddRange(BitConverter.GetBytes((int) callDescriptor.ReturnAddress));
                }

                // mov BYTE PTR [completionFlagBuffer], 0x01

                shellcode.AddRange(new byte[] {0xC6, 0x05});

                shellcode.AddRange(BitConverter.GetBytes((int) completionFlagBuffer));

                shellcode.Add(0x01);

                // popa

                shellcode.Add(0x61);

                // popf

                shellcode.Add(0x9D);

                // ret

                shellcode.Add(0xC3);
            }

            else
            {
                // pushf

                shellcode.Add(0x9C);

                // push rax

                shellcode.Add(0x50);

                // push rbx

                shellcode.Add(0x53);

                // push rcx

                shellcode.Add(0x51);

                // push rdx

                shellcode.Add(0x52);

                // push r8

                shellcode.AddRange(new byte[] {0x41, 0x50});

                // push r9

                shellcode.AddRange(new byte[] {0x41, 0x51});

                // push r10

                shellcode.AddRange(new byte[] {0x41, 0x52});

                // push r11

                shellcode.AddRange(new byte[] {0x41, 0x53});

                // replacedemble the function parameters

                Parameterreplacedembler.replacedembleFastCallParameters(callDescriptor, ref shellcode);

                // mov rax, functionAddress

                shellcode.AddRange(new byte[] {0x48, 0xB8});

                shellcode.AddRange(BitConverter.GetBytes((long) callDescriptor.FunctionAddress));

                // sub rsp, 0x28

                shellcode.AddRange(new byte[] {0x48, 0x83, 0xEC, 0x28});

                // call rax

                shellcode.AddRange(new byte[] {0xFF, 0xD0});

                // add rsp, 0x28

                shellcode.AddRange(new byte[] {0x48, 0x83, 0xC4, 0x28});

                if (callDescriptor.ReturnAddress != IntPtr.Zero)
                {
                    // mov [returnAddress], rax

                    shellcode.AddRange(new byte[] {0x48, 0xA3});

                    shellcode.AddRange(BitConverter.GetBytes((long) callDescriptor.ReturnAddress));
                }

                // mov rax, completionFlagBuffer

                shellcode.AddRange(new byte[] {0x48, 0xB8});

                shellcode.AddRange(BitConverter.GetBytes((long) completionFlagBuffer));

                // mov BYTE PTR [rax], 0x01

                shellcode.AddRange(new byte[] {0xC6, 0x00, 0x01});

                // pop r11

                shellcode.AddRange(new byte[] {0x41, 0x5B});

                // pop r10

                shellcode.AddRange(new byte[] {0x41, 0x5A});

                // pop r9

                shellcode.AddRange(new byte[] {0x41, 0x59});

                // pop r8

                shellcode.AddRange(new byte[] {0x41, 0x58});

                // pop rdx

                shellcode.Add(0x5A);

                // pop rcx

                shellcode.Add(0x59);

                // pop rbx

                shellcode.Add(0x5B);

                // pop rax

                shellcode.Add(0x58);

                // popf

                shellcode.Add(0x9D);

                // ret

                shellcode.Add(0xC3);
            }

            return shellcode.ToArray();
        }

19 Source : ParameterAssembler.cs
with MIT License
from Akaion

internal static void replacedembleFastCallParameters(CallDescriptor callDescriptor, ref List<byte> shellcode)
        {
            var stackParameters = new List<byte>();

            var parameterIndex = 0;

            if (callDescriptor.IsWow64Call)
            {
                foreach (var parameter in callDescriptor.Parameters)
                {
                    switch (parameterIndex)
                    {
                        case 0:
                        {
                            if (parameter == 0)
                            {
                                // xor ecx, ecx

                                shellcode.AddRange(new byte[] {0x31, 0xC9});
                            }

                            else
                            {
                                // mov ecx, parameter

                                shellcode.Add(0xB9);

                                shellcode.AddRange(BitConverter.GetBytes((int) parameter));
                            }

                            parameterIndex += 1;

                            break;
                        }

                        case 1:
                        {
                            if (parameter == 0)
                            {
                                // xor edx, edx

                                shellcode.AddRange(new byte[] {0x31, 0xD2});
                            }

                            else
                            {
                                // mov edx, parameter

                                shellcode.Add(0xBA);

                                shellcode.AddRange(BitConverter.GetBytes((int) parameter));
                            }

                            parameterIndex += 1;

                            break;
                        }

                        default:
                        {
                            if (parameter <= 0x7F)
                            {
                                // push parameter

                                stackParameters.InsertRange(0, new byte[] {0x6A, (byte) parameter});
                            }

                            else
                            {
                                // push parameter

                                var operation = new List<byte> {0x68};

                                operation.AddRange(BitConverter.GetBytes((int) parameter));

                                stackParameters.InsertRange(0, operation);
                            }

                            break;
                        }
                    }
                }
            }

            else
            {
                foreach (var parameter in callDescriptor.Parameters)
                {
                    switch (parameterIndex)
                    {
                        case 0:
                        {
                            if (parameter == 0)
                            {
                                // xor ecx, ecx

                                shellcode.AddRange(new byte[] {0x31, 0xC9});
                            }

                            else
                            {
                                // mov rcx, parameter

                                shellcode.AddRange(new byte[] {0x48, 0xB9});

                                shellcode.AddRange(BitConverter.GetBytes(parameter));
                            }

                            parameterIndex += 1;

                            break;
                        }

                        case 1:
                        {
                            if (parameter == 0)
                            {
                                // xor edx, edx

                                shellcode.AddRange(new byte[] {0x31, 0xD2});
                            }

                            else
                            {
                                // mov rdx, parameter

                                shellcode.AddRange(new byte[] {0x48, 0xBA});

                                shellcode.AddRange(BitConverter.GetBytes(parameter));
                            }

                            parameterIndex += 1;

                            break;
                        }

                        case 2:
                        {
                            if (parameter == 0)
                            {
                                // xor r8, r8

                                shellcode.AddRange(new byte[] {0x4D, 0x31, 0xC0});
                            }

                            else
                            {
                                // mov r8, parameter

                                shellcode.AddRange(new byte[] {0x49, 0xB8});

                                shellcode.AddRange(BitConverter.GetBytes(parameter));
                            }

                            parameterIndex += 1;

                            break;
                        }

                        case 3:
                        {
                            if (parameter == 0)
                            {
                                // xor r9, r9

                                shellcode.AddRange(new byte[] {0x4D, 0x31, 0xC9});
                            }

                            else
                            {
                                // mov r9, parameter

                                shellcode.AddRange(new byte[] {0x49, 0xB9});

                                shellcode.AddRange(BitConverter.GetBytes(parameter));
                            }

                            parameterIndex += 1;

                            break;
                        }

                        default:
                        {
                            if (parameter <= 0x7F)
                            {
                                // push parameter

                                stackParameters.InsertRange(0, new byte[] {0x6A, (byte) parameter});
                            }

                            else
                            {
                                var operation = new List<byte>();

                                if (parameter < int.MaxValue)
                                {
                                    // push parameter

                                    operation.Add(0x68);

                                    operation.AddRange(BitConverter.GetBytes((int) parameter));
                                }

                                else
                                {
                                    // mov rax, parameter

                                    operation.AddRange(new byte[] {0x48, 0xB8});

                                    operation.AddRange(BitConverter.GetBytes(parameter));

                                    // push rax

                                    operation.Add(0x50);
                                }

                                stackParameters.InsertRange(0, operation);
                            }

                            break;
                        }
                    }
                }
            }

            shellcode.AddRange(stackParameters);
        }

19 Source : ParameterAssembler.cs
with MIT License
from Akaion

internal static void replacedembleStdCallParameters(CallDescriptor callDescriptor, ref List<byte> shellcode)
        {
            foreach (var parameter in callDescriptor.Parameters.Select(p => p).Reverse())
            {
                if (parameter <= 0x7F)
                {
                    // push parameter

                    shellcode.AddRange(new byte[] {0x6A, (byte) parameter});
                }

                else
                {
                    // push parameter

                    shellcode.Add(0x68);

                    shellcode.AddRange(BitConverter.GetBytes((int) parameter));
                }
            }
        }

19 Source : ProcessManager.cs
with MIT License
from Akaion

internal IntPtr GetFunctionAddress(string moduleName, string functionName)
        {
            var module = Modules.Find(m => m.Name.Equals(moduleName, StringComparison.OrdinalIgnoreCase));

            if (module is null)
            {
                return IntPtr.Zero;
            }

            // Calculate the address of the function

            var function = module.PeImage.Value.ExportedFunctions.Find(f => f.Name != null && f.Name == functionName);

            var functionAddress = module.BaseAddress + function.Offset;

            // Determine if the function is forwarded to another function

            var exportDirectoryStartAddress = module.BaseAddress + module.PeImage.Value.Headers.PEHeader.ExportTableDirectory.RelativeVirtualAddress;

            var exportDirectoryEndAddress = exportDirectoryStartAddress + module.PeImage.Value.Headers.PEHeader.ExportTableDirectory.Size;

            if ((long) functionAddress < (long) exportDirectoryStartAddress || (long) functionAddress > (long) exportDirectoryEndAddress)
            {
                return functionAddress;
            }

            // Read the forwarded function

            var forwardedFunctionBytes = new List<byte>();

            while (true)
            {
                var currentByte = Memory.Read<byte>(functionAddress);

                if (currentByte == byte.MinValue)
                {
                    break;
                }

                forwardedFunctionBytes.Add(currentByte);

                functionAddress += 1;
            }

            var forwardedFunction = Encoding.ASCII.GetString(forwardedFunctionBytes.ToArray()).Split(".");

            return GetFunctionAddress(forwardedFunction[0] + ".dll", forwardedFunction[1]);
        }

19 Source : MethodDetour.cs
with MIT License
from Akaion

private void PrepareDetour()
        {
            // Ensure both methods are JIT compiled
            
            RuntimeHelpers.PrepareMethod(_originalMethodHandle);

            RuntimeHelpers.PrepareMethod(_targetMethodHandle);

            // Construct the shellcode needed to detour the method
            
            var shellcode = new List<byte>();
            
            if (Environment.Is64BitProcess)
            {
                // mov rax, targetMethodAddress
                
                shellcode.AddRange(new byte[] {0x48, 0xB8});
                
                shellcode.AddRange(BitConverter.GetBytes((long) _targetMethodHandle.GetFunctionPointer()));
                
                // jmp rax
                
                shellcode.AddRange(new byte[] {0xFF, 0xE0});
            }

            else
            {
                // mov eax, targetMethodAddress
                
                shellcode.Add(0xB8);
                
                shellcode.AddRange(BitConverter.GetBytes((int) _targetMethodHandle.GetFunctionPointer()));
                
                // jmp eax
                
                shellcode.AddRange(new byte[] {0xFF, 0xE0});
            }

            _detourBytes = shellcode.ToArray();
            
            // Save the bytes of the original method
            
            _originalMethodBytes = new byte[_detourBytes.Length];
            
            Marshal.Copy(_originalMethodHandle.GetFunctionPointer(), _originalMethodBytes, 0, _detourBytes.Length);
        }

19 Source : CreateThread.cs
with MIT License
from Akaion

private static byte[] replacedembleShellcode(CallDescriptor callDescriptor)
        {
            var shellcode = new List<byte>();

            if (callDescriptor.IsWow64Call)
            {
                // replacedemble the function parameters

                if (callDescriptor.CallingConvention == CallingConvention.FastCall)
                {
                    Parameterreplacedembler.replacedembleFastCallParameters(callDescriptor, ref shellcode);
                }

                else
                {
                    Parameterreplacedembler.replacedembleStdCallParameters(callDescriptor, ref shellcode);
                }

                // mov eax, functionAddress

                shellcode.Add(0xB8);

                shellcode.AddRange(BitConverter.GetBytes((int) callDescriptor.FunctionAddress));

                // call eax

                shellcode.AddRange(new byte[] {0xFF, 0xD0});

                if (callDescriptor.ReturnAddress != IntPtr.Zero)
                {
                    // mov [returnAddress], eax

                    shellcode.Add(0xA3);

                    shellcode.AddRange(BitConverter.GetBytes((int) callDescriptor.ReturnAddress));
                }

                // xor eax, eax

                shellcode.AddRange(new byte[] {0x33, 0xC0});

                // ret

                shellcode.Add(0xC3);
            }

            else
            {
                // replacedemble the function parameters

                Parameterreplacedembler.replacedembleFastCallParameters(callDescriptor, ref shellcode);

                // mov rax, functionAddress

                shellcode.AddRange(new byte[] {0x48, 0xB8});

                shellcode.AddRange(BitConverter.GetBytes((long) callDescriptor.FunctionAddress));

                // sub rsp, 0x28

                shellcode.AddRange(new byte[] {0x48, 0x83, 0xEC, 0x28});

                // call rax

                shellcode.AddRange(new byte[] {0xFF, 0xD0});

                // add rsp, 0x28

                shellcode.AddRange(new byte[] {0x48, 0x83, 0xC4, 0x28});

                if (callDescriptor.ReturnAddress != IntPtr.Zero)
                {
                    // mov [returnAddress], rax

                    shellcode.AddRange(new byte[] {0x48, 0xA3});

                    shellcode.AddRange(BitConverter.GetBytes((long) callDescriptor.ReturnAddress));
                }

                // xor eax, eax

                shellcode.AddRange(new byte[] {0x31, 0xC0});

                // ret

                shellcode.Add(0xC3);
            }

            return shellcode.ToArray();
        }

19 Source : BinaryConverter.cs
with MIT License
from 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 Source : JsonReader.cs
with MIT License
from akaskela

internal byte[] ReadArrayIntoByteArray()
        {
            List<byte> buffer = new List<byte>();

            while (true)
            {
                JsonToken t = GetContentToken();
                switch (t)
                {
                    case JsonToken.None:
                        throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
                    case JsonToken.Integer:
                        buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
                        break;
                    case JsonToken.EndArray:
                        byte[] d = buffer.ToArray();
                        SetToken(JsonToken.Bytes, d, false);
                        return d;
                    default:
                        throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
                }
            }
        }

19 Source : SerialController.cs
with GNU General Public License v3.0
from akmadian

public byte[] Write(byte[] buffer, int responselength)
        {
            /*_serialPort.DiscardInBuffer();
             THIS CREATES ERRORS FOR NOW
            _serialPort.DiscardOutBuffer();*/
            _Port.Write(buffer, 0, buffer.Length); //Second handshake
            Thread.Sleep(50);
            List<byte> reply = new List<byte>();

            try
            {
                for (int bytes = 0; bytes < responselength; bytes++)
                    reply.Add(Convert.ToByte(_Port.ReadByte()));
            }
            catch(TimeoutException)
            {
                
            }

            return reply.ToArray();
        }

19 Source : Color.cs
with GNU General Public License v3.0
from akmadian

public static byte[] AllOff()
        {
            List<int> outBytes = new List<int>();
            for (int i = 0; i < 40; i++)
            {
                outBytes.Add(0);
                outBytes.Add(0);
                outBytes.Add(0);
            }

            List<byte> outB = new List<byte>();

            foreach (int val in outBytes)
            {
                outB.Add(Convert.ToByte(val));
            }

            return outB.ToArray();
        }

19 Source : Color.cs
with GNU General Public License v3.0
from akmadian

internal byte[] Expanded()
        {
            List<byte> outBytes = new List<byte>();
            for (int i = 0; i < 40; i++)
            {
                outBytes.Add(Convert.ToByte(_G));
                outBytes.Add(Convert.ToByte(_R));
                outBytes.Add(Convert.ToByte(_B));
            }

            return outBytes.ToArray();
        }

19 Source : Extensions.cs
with GNU General Public License v3.0
from akmadian

public static List<byte> PadList(this List<byte> thisone, int ToLength)
        {
            int numToPad = ToLength - thisone.Count;
            for (int i = 0; i < numToPad; i++)
            {
                thisone.Add(0x00);
            }
            return thisone;
        }

19 Source : Extensions.cs
with GNU General Public License v3.0
from akmadian

public static byte[] PadColorArr(this byte[] thisone)
        {
            int numToPad = 120 - thisone.Length;
            List<byte> temp = new List<byte>();

            foreach (byte thing in thisone) { temp.Add(thing); }

            for (int curr = 0; curr < numToPad; curr++)
            {
                temp.Add(0x00);
            }
            return temp.ToArray();
        }

19 Source : HuePlusChannel.cs
with GNU General Public License v3.0
from akmadian

public byte[] BuildColorBytes(Color color) {
            List<byte> outList = new List<byte>();
            foreach (ISubDevice device in _SubDevices)
            {
                if (device.IsActive) // If active, add effect color
                {
                    byte[][] exp = color.ExpandedChunks(device.NumLeds);
                    for (int LED = 0; LED < device.NumLeds; LED++) {
                        if (device.Leds[LED])
                        {
                            outList.Add(exp[LED][0]);
                            outList.Add(exp[LED][1]);
                            outList.Add(exp[LED][2]);
                        }
                        else
                        {
                            outList.Add(0x00);
                            outList.Add(0x00);
                            outList.Add(0x00);
                        }
                    }
                }
                else { // If not active, add padding bytes
                    for (int led = 0; led < device.NumLeds * 3; led++) {
                        outList.Add(0x00);
                    }
                }
            }
            for (int pad = outList.Count; pad < 120; pad++) { // Pad out remainder
                outList.Add(0x00);
            }
            return outList.ToArray();
        }

19 Source : KrakenXChannel.cs
with GNU General Public License v3.0
from 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 Source : Auth.cs
with MIT License
from AL3X1

public async Task<bool> AuthenticateAsync()
        {
            _AuthCharacteristic = await Gatt.GetCharacteristicByServiceUuid(AUTH_SERVICE, AUTH_CHARACTERISTIC);
            await _AuthCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

            if (!IsAuthenticated())
            {
                Debug.WriteLine("Level 1 started");

                List<byte> sendKey = new List<byte>();
                sendKey.Add(0x01);
                sendKey.Add(0x08);
                sendKey.AddRange(AUTH_SECRET_KEY);

                if (await _AuthCharacteristic.WriteValueAsync(sendKey.ToArray().AsBuffer()) == GattCommunicationStatus.Success)
                {
                    Debug.WriteLine("Level 1 success");
                    _AuthCharacteristic.ValueChanged += AuthCharacteristic_ValueChanged;
                }
            }
            else
            {
                Debug.WriteLine("Already authorized (Level 1 successful)");
                Debug.WriteLine("Level 2 started");

                if (await SendAuthNumberAsync())
                    Debug.WriteLine("Level 2 success");

                _AuthCharacteristic.ValueChanged += AuthCharacteristic_ValueChanged;
            }

            _WaitHandle.WaitOne();
            return IsAuthenticated();
        }

19 Source : Auth.cs
with MIT License
from AL3X1

private async Task<bool> SendAuthNumberAsync()
        {
            Debug.WriteLine("Sending Auth Number");
            List<byte> authNumber = new List<byte>();
            authNumber.Add(0x02);
            authNumber.Add(0x08);

            return await _AuthCharacteristic.WriteValueAsync(authNumber.ToArray().AsBuffer()) == GattCommunicationStatus.Success;
        }

19 Source : Auth.cs
with MIT License
from AL3X1

private async Task<bool> SendEncryptedRandomKeyAsync(GattValueChangedEventArgs args)
        {
            // Thanks superhans205 for this solution: https://github.com/superhans205/FitForMiBand/blob/master/ClreplacedesCollection/CustomMiBand.vb#L370
            List<byte> randomKey = new List<byte>();
            List<byte> relevantResponsePart = new List<byte>();
            var responseValue = args.CharacteristicValue.ToArray();

            for (int i = 0; i < responseValue.Count(); i++)
            {
                if (i >= 3)
                    relevantResponsePart.Add(responseValue[i]);
            }

            randomKey.Add(0x03);
            randomKey.Add(0x08);
            randomKey.AddRange(Encrypt(relevantResponsePart.ToArray()));

            return await _AuthCharacteristic.WriteValueAsync(randomKey.ToArray().AsBuffer()) == GattCommunicationStatus.Success;
        }

19 Source : Auth.cs
with MIT License
from AL3X1

private async Task<bool> SendEncryptedRandomKeyAsync(GattValueChangedEventArgs args)
        {
            // Thanks superhans205 for this solution: https://github.com/superhans205/FitForMiBand/blob/master/ClreplacedesCollection/CustomMiBand.vb#L370
            List<byte> randomKey = new List<byte>();
            List<byte> relevantResponsePart = new List<byte>();
            var responseValue = args.CharacteristicValue.ToArray();

            for (int i = 0; i < responseValue.Count(); i++)
            {
                if (i >= 3)
                    relevantResponsePart.Add(responseValue[i]);
            }

            randomKey.Add(0x03);
            randomKey.Add(0x08);
            randomKey.AddRange(Encrypt(relevantResponsePart.ToArray()));

            return await _AuthCharacteristic.WriteValueAsync(randomKey.ToArray().AsBuffer()) == GattCommunicationStatus.Success;
        }

19 Source : Identity.cs
with MIT License
from AL3X1

public async Task<bool> SetUserInfo(DateTime dateOfBirth, Gender gender, int height, int weight)
        {
            int userId = (new Random()).Next(000000, 999999);
            var characteristic = await Gatt.GetCharacteristicByServiceUuid(MI_BAND_SERVICE, USERSETTINGS_CHARACTERISTIC);
            List<byte> data = new List<byte>();
            byte setUserInfoCmd = 79;

            data.Add(setUserInfoCmd);
            data.Add(0);
            data.Add(0);
            data.Add((byte)(dateOfBirth.Year & 255));
            data.Add((byte)((dateOfBirth.Year >> 8) & 255));
            data.Add((byte)dateOfBirth.Month);
            data.Add((byte)dateOfBirth.Day);
            data.Add((byte)gender);
            data.Add((byte)(height & 255));
            data.Add((byte)((height >> 8) & 255));
            data.Add((byte)((weight * 200) & 255));
            data.Add((byte)((weight * 200 >> 8) & 255));
            data.Add((byte)(userId & 255));
            data.Add((byte)((userId >> 8) & 255));
            data.Add((byte)((userId >> 16) & 255));
            data.Add((byte)((userId >> 24) & 255));

            Debug.WriteLine("Writing user info to Band");

            return await characteristic.WriteValueAsync(data.ToArray().AsBuffer()) == GattCommunicationStatus.Success;
        }

19 Source : Identity.cs
with MIT License
from AL3X1

private async Task<bool> SendEncryptedRandomKeyAsync(GattValueChangedEventArgs args)
        {
            List<byte> randomKey = new List<byte>();
            List<byte> relevantResponsePart = new List<byte>();
            var responseValue = args.CharacteristicValue.ToArray();

            for (int i = 0; i < responseValue.Count(); i++)
            {
                if (i >= 3)
                    relevantResponsePart.Add(responseValue[i]);
            }

            randomKey.Add(0x03);
            randomKey.Add(0x08);
            randomKey.AddRange(Encrypt(relevantResponsePart.ToArray()));

            return await _AuthCharacteristic.WriteValueAsync(randomKey.ToArray().AsBuffer()) == GattCommunicationStatus.Success;
        }

19 Source : Identity.cs
with MIT License
from AL3X1

private async Task<bool> SendEncryptedRandomKeyAsync(GattValueChangedEventArgs args)
        {
            List<byte> randomKey = new List<byte>();
            List<byte> relevantResponsePart = new List<byte>();
            var responseValue = args.CharacteristicValue.ToArray();

            for (int i = 0; i < responseValue.Count(); i++)
            {
                if (i >= 3)
                    relevantResponsePart.Add(responseValue[i]);
            }

            randomKey.Add(0x03);
            randomKey.Add(0x08);
            randomKey.AddRange(Encrypt(relevantResponsePart.ToArray()));

            return await _AuthCharacteristic.WriteValueAsync(randomKey.ToArray().AsBuffer()) == GattCommunicationStatus.Success;
        }

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

public byte[] ReadBytes(long length, bool isBytes = false)
        {
            if (isBytes)
            {
                length *= 8;
            }
            List<byte> data = new List<byte>();
            for (long i = 0; i < length;)
            {
                byte value = 0;
                for (int p = 0; p < 8 && i < length; i++, p++)
                {
                    if (!MSB)
                    {
                        value |= (byte)(ReadBit() << p);
                    }
                    else
                    {
                        value |= (byte)(ReadBit() << (7 - p));
                    }
                }
                data.Add(value);
            }
            return data.ToArray();
        }

19 Source : BigEndianBuffer.cs
with MIT License
from allartprotocol

public void WriteUInt(uint i)
        {
            _bytes.Add((byte)((i >> 0x18) & 0xff));
            _bytes.Add((byte)((i >> 0x10) & 0xff));
            _bytes.Add((byte)((i >> 8) & 0xff));
            _bytes.Add((byte)(i & 0xff));
        }

19 Source : BigEndianBuffer.cs
with MIT License
from allartprotocol

public void Write(byte b)
        {
            _bytes.Add(b);
        }

19 Source : ShortVecEncoding.cs
with MIT License
from allartprotocol

public static void Encodelength(ref List<byte> bytes, int len)
        {
            byte rem_len = (byte)len;
            for (int i = 0; i < bytes.Count; i++)
            {
                int elem = rem_len & 0x7f;
                rem_len >>= 7;
                if (rem_len == 0)
                {
                    bytes.Add((byte)elem);
                    break;
                }
                else
                {
                    elem |= 0x80;
                    bytes.Add((byte)elem);
                }
            }
        }

19 Source : EventGenerator.cs
with MIT License
from altskop

private List<DeathEvent> processDeaths()
        {
            List<DeathEvent> deathEvents = new List<DeathEvent>();
            int previouslyDeadNumber = previousData.getDeadPlayers().Count;
            int currentlyDeadNumber = currentData.getDeadPlayers().Count;
            if (previouslyDeadNumber < currentlyDeadNumber)
            {
                List<byte> previouslyDeadColors = new List<byte>();
                foreach (PlayerInformation player in previousData.getDeadPlayers())
                {
                    previouslyDeadColors.Add(player.colorId);
                }

                List<byte> deadColors = new List<byte>();
                foreach (PlayerInformation player in currentData.getDeadPlayers())
                {
                    deadColors.Add(player.colorId);
                }

                foreach (byte colorId in deadColors)
                {
                    if (!previouslyDeadColors.Contains(colorId))
                    {
                        PlayerInformation victim = currentData.getPlayerByColor(colorId);
                        if (!previousData.getPlayerByColor(victim.colorId).position.IsGarbage())
                        {
                            DeathEvent deathEvent = new DeathEvent(victim, findKiller(victim), currentData.getNearbyPlayers(colorId));
                            if (currentData.botPlayer.position.isVisible(deathEvent.position, currentData.lightRadius))
                                deathEvents.Add(deathEvent);
                        }
                    }
                }
            }
            
            return deathEvents;
        }

19 Source : ModbusClient.cs
with MIT License
from AndreasAmMueller

private async Task ProcessSendQueue()
		{
			try
			{
				logger?.LogTrace("ModbusClient.ProcessSendQueue enter");
				while (!sendCts.IsCancellationRequested)
				{
					RequestTask task = null;
					try
					{
						SpinWait.SpinUntil(() => sendCts.IsCancellationRequested || sendQueue.Any());
						if (sendCts.IsCancellationRequested)
							return;

						lock (queueLock)
						{
							task = sendQueue.First();
							sendQueue.Remove(task);
						}

						logger?.LogTrace(task.Request.ToString());

						// clear all data
						await serialPort.BaseStream.FlushAsync();
						serialPort.DiscardInBuffer();
						serialPort.DiscardOutBuffer();

						logger?.LogDebug($"Sending {task.Request}");
						byte[] bytes = task.Request.Serialize();
						await serialPort.WriteAsync(bytes, 0, bytes.Length, sendCts.Token);
						logger?.LogDebug("Request sent.");

						var responseBytes = new List<byte>
						{
							// Device/Slave ID
							await ReadByte(sendCts.Token)
						};

						// Function number
						byte fn = await ReadByte(sendCts.Token);
						responseBytes.Add(fn);

						byte expectedBytes = 0;
						var function = (FunctionCode)((fn & Consts.ErrorMask) > 0 ? fn ^ Consts.ErrorMask : fn);
						switch (function)
						{
							case FunctionCode.ReadCoils:
							case FunctionCode.ReadDiscreteInputs:
							case FunctionCode.ReadHoldingRegisters:
							case FunctionCode.ReadInputRegisters:
								expectedBytes = await ReadByte(sendCts.Token);
								responseBytes.Add(expectedBytes);
								break;
							case FunctionCode.WriteSingleCoil:
							case FunctionCode.WriteSingleRegister:
							case FunctionCode.WriteMultipleCoils:
							case FunctionCode.WriteMultipleRegisters:
								expectedBytes = 4;
								break;
							case FunctionCode.EncapsulatedInterface:
								responseBytes.AddRange(await ReadBytes(6, sendCts.Token));
								byte count = responseBytes.Last();
								for (int i = 0; i < count; i++)
								{
									// id
									responseBytes.Add(await ReadByte(sendCts.Token));
									// length
									expectedBytes = await ReadByte(sendCts.Token);
									responseBytes.Add(expectedBytes);
									// value
									responseBytes.AddRange(await ReadBytes(expectedBytes, sendCts.Token));
								}
								expectedBytes = 0;
								break;
							default:
								if ((fn & Consts.ErrorMask) == 0)
									throw new NotImplementedException();

								expectedBytes = 1;
								break;
						}

						expectedBytes += 2; // CRC Check

						responseBytes.AddRange(await ReadBytes(expectedBytes, sendCts.Token));
						logger?.LogDebug("Response received.");

						var response = new Response(responseBytes.ToArray());
						task.TaskCompletionSource.TrySetResult(response);
					}
					catch (OperationCanceledException) when (sendCts.IsCancellationRequested)
					{
						task?.TaskCompletionSource.TrySetResult(new Response(new byte[] { 0, 0, 0, 0, 0, 0 }));
					}
					catch (TimeoutException)
					{
						task?.TaskCompletionSource.TrySetResult(new Response(new byte[] { 0, 0, 0, 0, 0, 0 }));
					}
					catch (Exception ex)
					{
						logger?.LogError(ex, $"Unexpected error ({ex.GetType().Name}) on send: {ex.GetMessage()}");
						task?.TaskCompletionSource.TrySetResult(new Response(new byte[] { 0, 0, 0, 0, 0, 0 }));
					}
					finally
					{
						task?.Registration.Dispose();
						try
						{
							await Task.Delay(InterRequestDelay, sendCts.Token);
						}
						catch
						{ }
					}
				}
			}
			finally
			{
				logger?.LogTrace("ModbusClient.ProcessSendQueue leave");
			}
		}

19 Source : BinaryStream.cs
with MIT License
from AndnixSH

public string ReadStringToNull(ulong addr)
        {
            Position = addr;
            var bytes = new List<byte>();
            byte b;
            while ((b = ReadByte()) != 0)
                bytes.Add(b);
            return Encoding.UTF8.GetString(bytes.ToArray());
        }

19 Source : ModbusTcpTests.cs
with MIT License
from AndreasAmMueller

[TestMethod]
		public async Task ClientReadDeviceInformationBasicTest()
		{
			byte[] expectedRequest = new byte[] { 0, 0, 0, 5, 13, 43, 14, 1, 0 };
			var expectedResponse = new Dictionary<DeviceIDObject, string>
			{
				{ DeviceIDObject.VendorName, "AM.WD" },
				{ DeviceIDObject.ProductCode, "Mini-Test" },
				{ DeviceIDObject.MajorMinorRevision, "1.2.3.4" }
			};

			using var server = new MiniTestServer
			{
				RequestHandler = (request, clientIp) =>
				{
					Collectionreplacedert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect");
					Console.WriteLine("Server sending response");

					var bytes = new List<byte>();
					bytes.AddRange(request.Take(2));
					bytes.AddRange(new byte[] { 0, 0, 0, 0, 13, 43, 14, 1, 1, 0, 0, (byte)expectedResponse.Count });
					int len = 8;
					foreach (var kvp in expectedResponse)
					{
						byte[] b = Encoding.ASCII.GetBytes(kvp.Value);
						bytes.Add((byte)kvp.Key);
						len++;
						bytes.Add((byte)b.Length);
						len++;
						bytes.AddRange(b);
						len += b.Length;
					}
					bytes[5] = (byte)len;

					return bytes.ToArray();
				}
			};
			server.Start();

			using var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger());
			await client.Connect();
			replacedert.IsTrue(client.IsConnected);

			var deviceInfo = await client.ReadDeviceInformation(13, DeviceIDCategory.Basic);
			replacedert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError);
			Collectionreplacedert.AreEqual(expectedResponse, deviceInfo, "Response is incorrect");
		}

19 Source : ModbusTcpTests.cs
with MIT License
from AndreasAmMueller

[TestMethod]
		public async Task ClientReadDeviceInformationIndividualTest()
		{
			byte[] expectedRequest = new byte[] { 0, 0, 0, 5, 13, 43, 14, 4, (byte)DeviceIDObject.ModelName };
			var expectedResponse = new Dictionary<DeviceIDObject, string>
			{
				{ DeviceIDObject.ModelName, "TestModel" }
			};

			using var server = new MiniTestServer
			{
				RequestHandler = (request, clientIp) =>
				{
					Collectionreplacedert.AreEqual(expectedRequest, request.Skip(2).ToArray(), "Request is incorrect");
					Console.WriteLine("Server sending response");

					var bytes = new List<byte>();
					bytes.AddRange(request.Take(2));
					bytes.AddRange(new byte[] { 0, 0, 0, 0, 13, 43, 14, 4, 2, 0, 0, (byte)expectedResponse.Count });
					int len = 8;
					foreach (var kvp in expectedResponse)
					{
						byte[] b = Encoding.ASCII.GetBytes(kvp.Value);
						bytes.Add((byte)kvp.Key);
						len++;
						bytes.Add((byte)b.Length);
						len++;
						bytes.AddRange(b);
						len += b.Length;
					}
					bytes[5] = (byte)len;

					return bytes.ToArray();
				}
			};
			server.Start();

			using var client = new ModbusClient(IPAddress.Loopback, server.Port, new ConsoleLogger());
			await client.Connect();
			replacedert.IsTrue(client.IsConnected);

			var deviceInfo = await client.ReadDeviceInformation(13, DeviceIDCategory.Individual, DeviceIDObject.ModelName);
			replacedert.IsTrue(string.IsNullOrWhiteSpace(server.LastError), server.LastError);
			Collectionreplacedert.AreEqual(expectedResponse, deviceInfo, "Response is incorrect");
		}

19 Source : ProfilingTypeSettingsCollection.cs
with GNU General Public License v3.0
from AndreiFedarets

public override void Validate()
        {
            base.Validate();
            lock (Collection)
            {
                List<byte> usedDataMarkers = new List<byte>();
                foreach (ProfilingTypeSettings settings in Collection.Values)
                {
                    if (usedDataMarkers.Contains(settings.DataMarker))
                    {
                        throw new TempException();
                    }
                    usedDataMarkers.Add(settings.DataMarker);
                }
            }
        }

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

static byte[] GetDecodedData ( ImageBlock imgBlock )
	{
		// Combine LZW compressed data
		List<byte> lzwData = new List<byte>();
		for( int i = 0 ; i<imgBlock.m_imageDataList.Count ; i++ )
		{
			for( int k = 0 ; k<imgBlock.m_imageDataList[i].m_imageData.Length ; k++ )
			{
				lzwData.Add( imgBlock.m_imageDataList[i].m_imageData[k] );
			}
		}

		// LZW decode
		int needDataSize = imgBlock.m_imageHeight * imgBlock.m_imageWidth;
		byte[] decodedData = DecodeGifLZW( lzwData , imgBlock.m_lzwMinimumCodeSize , needDataSize );

		// Sort interlace GIF
		if( imgBlock.m_interlaceFlag )
		{
			decodedData = SortInterlaceGifData( decodedData , imgBlock.m_imageWidth );
		}
		return decodedData;
	}

19 Source : HttpBase.cs
with MIT License
from andruzzzhka

private static string[] readHeaders (Stream stream, int maxLength)
    {
      var buff = new List<byte> ();
      var cnt = 0;
      Action<int> add = i => {
        if (i == -1)
          throw new EndOfStreamException ("The header cannot be read from the data source.");

        buff.Add ((byte) i);
        cnt++;
      };

      var read = false;
      while (cnt < maxLength) {
        if (stream.ReadByte ().EqualsWith ('\r', add) &&
            stream.ReadByte ().EqualsWith ('\n', add) &&
            stream.ReadByte ().EqualsWith ('\r', add) &&
            stream.ReadByte ().EqualsWith ('\n', add)) {
          read = true;
          break;
        }
      }

      if (!read)
        throw new WebSocketException ("The length of header part is greater than the max length.");

      return Encoding.UTF8.GetString (buff.ToArray ())
             .Replace (CrLf + " ", " ")
             .Replace (CrLf + "\t", " ")
             .Split (new[] { CrLf }, StringSplitOptions.RemoveEmptyEntries);
    }

19 Source : TokenInfoDictionaryCompilerBase.cs
with Apache License 2.0
from AnkiUniversal

private List<byte> CreatePosFeatureIds(List<int> posFeatureIds)
        {
            List<byte> posFeatureIdBytes = new List<byte>();
            foreach (int posFeatureId in posFeatureIds)
            {
                posFeatureIdBytes.Add((byte)posFeatureId);
            }
            return posFeatureIdBytes;
        }

19 Source : H5Utils.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

public static string ReadNullTerminatedString(H5BinaryReader reader, bool pad, int padSize = 8, CharacterSetEncoding encoding = CharacterSetEncoding.ASCII)
        {
            var data = new List<byte>();
            var byteValue = reader.ReadByte();

            while (byteValue != '\0')
            {
                data.Add(byteValue);
                byteValue = reader.ReadByte();
            }

            var result = encoding switch
            {
                CharacterSetEncoding.ASCII  => Encoding.ASCII.GetString(data.ToArray()),
                CharacterSetEncoding.UTF8   => Encoding.UTF8.GetString(data.ToArray()),
                _ => throw new FormatException($"The character set encoding '{encoding}' is not supported.")
            };

19 Source : ModbusServer.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn

protected void AddUnit(byte unitIdentifer)
        {
            if (!_unitIdentifiers.Contains(unitIdentifer))
            {
                _unitIdentifiers.Add(unitIdentifer);
                _inputRegisterBufferMap[unitIdentifer] = new byte[_inputRegisterSize];
                _holdingRegisterBufferMap[unitIdentifer] = new byte[_holdingRegisterSize];
                _coilBufferMap[unitIdentifer] = new byte[_coilSize];
                _discreteInputBufferMap[unitIdentifer] = new byte[_discreteInputSize];
            }
        }

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

private string ReadZeroTerminatedString()
        {
            var list = new System.Collections.Generic.List<byte>();
            bool done = false;
            do
            {
                // workitem 7740
                int n = _stream.Read(_buf1, 0, 1);
                if (n != 1)
                    throw new ZlibException("Unexpected EOF reading GZIP header.");
                else
                {
                    if (_buf1[0] == 0)
                        done = true;
                    else
                        list.Add(_buf1[0]);
                }
            } while (!done);
            byte[] a = list.ToArray();
            return GZipStream.iso8859dash1.GetString(a, 0, a.Length);
        }

19 Source : B3dm.cs
with MIT License
from arcplus

public byte[] Convert(Options options)
        {
            if (options == null) options = new Options();

            var featureTableJson = options.FeatureTableJson;
            var featureTableBinary = options.FeatureTableBinary;
            var batchTableJson = options.BatchTableJson;
            var batchTableBinary = options.BatchTableBinary;

            var featureTableJsonByteLength = featureTableJson.Count;
            var featureTableBinaryByteLength = featureTableBinary.Count;
            var batchTableJsonByteLength = batchTableJson.Count;
            var batchTableBinaryByteLength = batchTableBinary.Count;
            var gltfByteLength = _glb.Count;
            var byteLength = HeaderByteLength + featureTableJsonByteLength 
                + featureTableBinaryByteLength + batchTableJsonByteLength 
                + batchTableBinaryByteLength + gltfByteLength;

            var all = new List<byte>();
            // Header
            all.Add(System.Convert.ToByte('b'));
            all.Add(System.Convert.ToByte('3'));
            all.Add(System.Convert.ToByte('d'));
            all.Add(System.Convert.ToByte('m'));
            all.AddRange(BitConverter.GetBytes((uint)Version));
            all.AddRange(BitConverter.GetBytes((uint)byteLength));
            all.AddRange(BitConverter.GetBytes((uint)featureTableJsonByteLength));
            all.AddRange(BitConverter.GetBytes((uint)featureTableBinaryByteLength));
            all.AddRange(BitConverter.GetBytes((uint)batchTableJsonByteLength));
            all.AddRange(BitConverter.GetBytes((uint)batchTableBinaryByteLength));

            all.AddRange(featureTableJson);
            all.AddRange(featureTableBinary);
            all.AddRange(batchTableJson);
            all.AddRange(batchTableBinary);
            all.AddRange(_glb);

            return all.ToArray();
        }

19 Source : CullArea.cs
with MIT License
from ArcturusZhang

public void GetActiveCells(List<byte> activeCells, bool yIsUpAxis, Vector3 position)
        {
            if (this.NodeType != ENodeType.Leaf)
            {
                foreach (CellTreeNode node in this.Childs)
                {
                    node.GetActiveCells(activeCells, yIsUpAxis, position);
                }
            }
            else
            {
                if (this.IsPointNearCell(yIsUpAxis, position))
                {
                    if (this.IsPointInsideCell(yIsUpAxis, position))
                    {
                        activeCells.Insert(0, this.Id);

                        CellTreeNode p = this.Parent;
                        while (p != null)
                        {
                            activeCells.Insert(0, p.Id);

                            p = p.Parent;
                        }
                    }
                    else
                    {
                        activeCells.Add(this.Id);
                    }
                }
            }
        }

19 Source : CullingHandler.cs
with MIT License
from ArcturusZhang

private bool HaveActiveCellsChanged()
        {
            if (this.cullArea.NumberOfSubdivisions == 0)
            {
                return false;
            }

            this.previousActiveCells = new List<byte>(this.activeCells);
            this.activeCells = this.cullArea.GetActiveCells(transform.position);

            // If the player leaves the area we insert the whole area itself as an active cell.
            // This can be removed if it is sure that the player is not able to leave the area.
            while (this.activeCells.Count <= this.cullArea.NumberOfSubdivisions)
            {
                this.activeCells.Add(this.cullArea.FIRST_GROUP_ID);
            }

            if (this.activeCells.Count != this.previousActiveCells.Count)
            {
                return true;
            }

            if (this.activeCells[this.cullArea.NumberOfSubdivisions] != this.previousActiveCells[this.cullArea.NumberOfSubdivisions])
            {
                return true;
            }

            return false;
        }

19 Source : CullingHandler.cs
with MIT License
from ArcturusZhang

private void UpdateInterestGroups()
        {
            List<byte> disable = new List<byte>(0);

            foreach (byte groupId in this.previousActiveCells)
            {
                if (!this.activeCells.Contains(groupId))
                {
                    disable.Add(groupId);
                }
            }

            PhotonNetwork.SetInterestGroups(disable.ToArray(), this.activeCells.ToArray());
        }

19 Source : CullingHandler.cs
with MIT License
from ArcturusZhang

public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
        {
            // If the player leaves the area we insert the whole area itself as an active cell.
            // This can be removed if it is sure that the player is not able to leave the area.
            while (this.activeCells.Count <= this.cullArea.NumberOfSubdivisions)
            {
                this.activeCells.Add(this.cullArea.FIRST_GROUP_ID);
            }

            if (this.cullArea.NumberOfSubdivisions == 1)
            {
                this.orderIndex = (++this.orderIndex % this.cullArea.SUBDIVISION_FIRST_LEVEL_ORDER.Length);
                this.pView.Group = this.activeCells[this.cullArea.SUBDIVISION_FIRST_LEVEL_ORDER[this.orderIndex]];
            }
            else if (this.cullArea.NumberOfSubdivisions == 2)
            {
                this.orderIndex = (++this.orderIndex % this.cullArea.SUBDIVISION_SECOND_LEVEL_ORDER.Length);
                this.pView.Group = this.activeCells[this.cullArea.SUBDIVISION_SECOND_LEVEL_ORDER[this.orderIndex]];
            }
            else if (this.cullArea.NumberOfSubdivisions == 3)
            {
                this.orderIndex = (++this.orderIndex % this.cullArea.SUBDIVISION_THIRD_LEVEL_ORDER.Length);
                this.pView.Group = this.activeCells[this.cullArea.SUBDIVISION_THIRD_LEVEL_ORDER[this.orderIndex]];
            }
        }

19 Source : Converter.cs
with MIT License
from arcplus

public static void PaddingBuffers(List<byte> buffers, int boundary = 4)
        {
            var length = buffers.Count;
            var remainder = length % boundary;
            if (remainder != 0)
            {
                var padding = boundary - remainder;
                for (var i = 0; i < padding; i++)
                {
                    buffers.Add(0);
                }
            }
        }

19 Source : Disassembler.cs
with MIT License
from arcusmaximus

private bool ProcessGetString()
        {
            int pc = (int)_reader.BaseStream.Position - 1;
            int offset = _reader.ReadInt16();
            int target = pc + offset;

            _reader.BaseStream.Position = target;
            List<byte> chars = new List<byte>();
            byte c;
            while ((c = _reader.ReadByte()) != 0)
            {
                chars.Add(c);
            }
            string str = Encoding.GetString(chars.ToArray());
            _currentInstr.Append($"getstring \"{str.Replace("\"", "\\\"")}\"      // {target:X} - {target + chars.Count:X}");

            _reader.BaseStream.Position = pc + 3;
            return true;
        }

19 Source : ByteArrayConverter.cs
with MIT License
from 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 Source : QRCodeData.cs
with MIT License
from arqueror

public byte[] GetRawData(Compression compressMode)
        {
            var bytes = new List<byte>();

            //Add header - signature ("QRR")
            bytes.AddRange(new byte[] { 0x51, 0x52, 0x52, 0x00 });

            //Add header - rowsize
            bytes.Add((byte)ModuleMatrix.Count);

            //Build data queue
            var dataQueue = new Queue<int>();
            foreach (var row in ModuleMatrix)
            {
                foreach (var module in row)
                {
                    dataQueue.Enqueue((bool)module ? 1 : 0);
                }
            }
            for (int i = 0; i < 8 - (ModuleMatrix.Count * ModuleMatrix.Count) % 8; i++)
            {
                dataQueue.Enqueue(0);
            }

            //Process queue
            while (dataQueue.Count > 0)
            {
                byte b = 0;
                for (int i = 7; i >= 0; i--)
                {
                    b += (byte)(dataQueue.Dequeue() << i);
                }
                bytes.Add(b);
            }
            var rawData = bytes.ToArray();

            //Compress stream (optional)
            if (compressMode == Compression.Deflate)
            {
                using (var output = new MemoryStream())
                {
                    using (var dstream = new DeflateStream(output, CompressionMode.Compress))
                    {
                        dstream.Write(rawData, 0, rawData.Length);
                    }
                    rawData = output.ToArray();
                }
            }
            else if (compressMode == Compression.GZip)
            {
                using (var output = new MemoryStream())
                {
                    using (GZipStream gzipStream = new GZipStream(output, CompressionMode.Compress, true))
                    {
                        gzipStream.Write(rawData, 0, rawData.Length);
                    }
                    rawData = output.ToArray();
                }
            }
            return rawData;
        }

19 Source : Main.cs
with MIT License
from arsium

private void generateKeyButton_Click(object sender, EventArgs e)
        {
            try
            {

                Random randomGenerator = new Random();
                List<byte> RES = new List<byte>();
                StringBuilder S = new StringBuilder();

                for (var i = 0; i <= 450; i++)
                {
                    S.Append(Utilities.randomString[randomGenerator.Next(0, Utilities.randomString.Length)]);
                }

                switch (keySizeComboBox.SelectedItem)
                {
                    case "Any":
                        int tempVar = 32 + randomGenerator.Next(0, 128) - 1;
                        for (var i = 0; i <= tempVar; i++)
                        {
                            RES.Add(Convert.ToByte(S.ToString()[i]));
                        }
                        keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
                        break;

                    case "32-448":
                        int tempVar2 = (randomGenerator.Next(32, 448) - 1) / 8;
                        for (var i = 0; i <= tempVar2; i++)
                        {
                            RES.Add(Convert.ToByte(S.ToString()[i]));
                        }
                        keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
                        break;

                    case "128-512":
                        int tempVar3 = (randomGenerator.Next(128, 512) - 1) / 8;
                        for (var i = 0; i <= tempVar3; i++)
                        {
                            RES.Add(Convert.ToByte(S.ToString()[i]));
                        }
                        keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
                        break;

                    case "40-2048":
                        int tempVar4 = (randomGenerator.Next(40, 2048) - 1) / 8;
                        for (var i = 0; i <= tempVar4; i++)
                        {
                            RES.Add(Convert.ToByte(S.ToString()[i]));
                        }
                        keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
                        break;

                    case "8-2048": 
                        int tempVar5 = (randomGenerator.Next(8, 2048) - 1) / 8;
                        for (var i = 0; i <= tempVar5; i++)
                        {
                            RES.Add(Convert.ToByte(S.ToString()[i]));
                        }
                        keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
                        break;

                    default:
                        int tempVar6 = (int.Parse(keySizeComboBox.SelectedItem.ToString()) - 1) / 8;
                        for (var i = 0; i <= tempVar6; i++)
                        {
                            RES.Add(Convert.ToByte(S.ToString()[i]));
                        }
                        keyTextBox.Text = Encoding.Default.GetString(RES.ToArray());
                        break;
                }

                Utilities.key = Encoding.Default.GetString(RES.ToArray());
                Utilities.settings.encryptionFileManagerKey = Utilities.key;
                Utilities.settings.encryptionFileManagerKeySize = keySizeComboBox.SelectedItem.ToString();
                Utilities.settings.algorithm = (Algorithm)(algoComboBox.SelectedIndex);
                string savedSettings = JsonConvert.SerializeObject(Utilities.settings);
                File.WriteAllText(Utilities.GPath + "\\config.json", savedSettings);

            }
            catch {}
        }

19 Source : AssetBinaryReader.cs
with MIT License
from atenfyr

public string XFERSTRING()
        {
            List<byte> readData = new List<byte>();
            while (true)
            {
                byte newVal = this.ReadByte();
                if (newVal == 0) break;
                readData.Add(newVal);
            }
            return Encoding.ASCII.GetString(readData.ToArray());
        }

19 Source : AssetBinaryReader.cs
with MIT License
from atenfyr

public string XFERUNICODESTRING()
        {
            List<byte> readData = new List<byte>();
            while (true)
            {
                byte newVal1 = this.ReadByte();
                byte newVal2 = this.ReadByte();
                if (newVal1 == 0 && newVal2 == 0) break;
                readData.Add(newVal1);
                readData.Add(newVal2);
            }
            return Encoding.Unicode.GetString(readData.ToArray());
        }

See More Examples