System.IO.BinaryWriter.Write(byte)

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

1779 Examples 7

19 View Source File : CelesteNetBinaryWriter.cs
License : MIT License
Project Creator : 0x0ade

public virtual void WriteSizeDummy(byte size) {
            Flush();
            SizeDummyIndex = BaseStream.Position;

            if (size == 1) {
                SizeDummySize = 1;
                Write((byte) 0);

            } else if (size == 4) {
                SizeDummySize = 4;
                Write((uint) 0);

            } else {
                SizeDummySize = 2;
                Write((ushort) 0);
            }
        }

19 View Source File : CelesteNetBinaryWriter.cs
License : MIT License
Project Creator : 0x0ade

public virtual void UpdateSizeDummy() {
            if (SizeDummySize == 0)
                return;

            Flush();
            long end = BaseStream.Position;
            long length = end - (SizeDummyIndex + SizeDummySize);

            BaseStream.Seek(SizeDummyIndex, SeekOrigin.Begin);

            if (SizeDummySize == 1) {
                if (length > byte.MaxValue)
                    length = byte.MaxValue;
                Write((byte) length);

            } else if (SizeDummySize == 4) {
                if (length > uint.MaxValue)
                    length = uint.MaxValue;
                Write((uint) length);

            } else {
                if (length > ushort.MaxValue)
                    length = ushort.MaxValue;
                Write((ushort) length);
            }

            Flush();
            BaseStream.Seek(end, SeekOrigin.Begin);
        }

19 View Source File : CelesteNetBinaryWriter.cs
License : MIT License
Project Creator : 0x0ade

public virtual void WriteNetMappedString(string? text) {
            if (Strings == null || !Strings.TryMap(text, out int id)) {
                WriteNetString(text);
                return;
            }

            Write((byte) 0xFF);
            Write7BitEncodedInt(id);
        }

19 View Source File : UEStringProperty.cs
License : MIT License
Project Creator : 13xforever

public override void Serialize(BinaryWriter writer)
        {
            if (Value == null)
            {
                writer.Write(0L);
                writer.Write((byte)0);
            }
            else
            {
                var bytes = Utf8.GetBytes(Value);
                writer.Write(bytes.Length + 6L);
                writer.Write((byte)0);
                writer.Write(bytes.Length+1);
                if (bytes.Length > 0)
                    writer.Write(bytes);
                writer.Write((byte)0);
            }
        }

19 View Source File : BinaryReaderEx.cs
License : MIT License
Project Creator : 13xforever

public static void WriteUEString(this BinaryWriter writer, string value)
        {
            if (value == null)
            {
                writer.Write(0);
                return;
            }

            var valueBytes = Utf8.GetBytes(value);
            writer.Write(valueBytes.Length + 1);
            if (valueBytes.Length > 0)
                writer.Write(valueBytes);
            writer.Write((byte)0);
        }

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

public byte[] Get_Tlv(QQUser user)
        {
            var data = new BinaryWriter(new MemoryStream());
            if (WSubVer == 0x0001)
            {
                data.BeWrite(WSubVer); //wSubVer
                data.Write(Util.IPStringToByteArray(user.TXProtocol.DwServerIP)); //LastServerIP - 服务器最后的登录IP,可以为0
                data.Write((byte) user.TXProtocol.RedirectIP.Count); //cRedirectCount - 重定向的次数(IP的数量)
                foreach (var ip in user.TXProtocol.RedirectIP)
                {
                    data.Write(ip);
                }

                data.Write(user.TXProtocol.CPingType); //cPingType 
            }
            else
            {
                throw new Exception($"{Name} 无法识别的版本号 {WSubVer}");
            }

            FillHead(Command);
            FillBody(data.BaseStream.ToBytesArray(), data.BaseStream.Length);
            SetLength();
            return GetBuffer();
        }

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

public byte[] Get_Tlv(QQUser user)
        {
            var data = new BinaryWriter(new MemoryStream());
            data.Write((byte) 1);
            data.BeWrite(1);
            FillHead(Command);
            FillBody(data.BaseStream.ToBytesArray(), data.BaseStream.Length);
            SetLength();
            return GetBuffer();
        }

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

public byte[] Get_Tlv(QQUser user)
        {
            var data = new BinaryWriter(new MemoryStream());
            if (WSubVer == 0x01)
            {
                data.Write((byte) 1);
                data.Write((byte) 1);
                data.Write((byte) 2);
                data.WriteKey(user.TXProtocol.BufMacGuid);
                data.BeWrite(2);
            }
            else
            {
                throw new Exception($"{Name} 无法识别的版本号 {WSubVer}");
            }

            FillHead(Command);
            FillBody(data.BaseStream.ToBytesArray(), data.BaseStream.Length);
            SetLength();
            return GetBuffer();
        }

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

public byte[] Get_Tlv(QQUser user)
        {
            var data = new BinaryWriter(new MemoryStream());
            data.Write((byte) 1);
            data.BeWrite(0);


            FillHead(Command);
            FillBody(data.BaseStream.ToBytesArray(), data.BaseStream.Length);
            SetLength();
            return GetBuffer();
        }

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

protected override void PutBody()
        {
            BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x07 });
            var data = new BinaryWriter(new MemoryStream());
            data.Write(new byte[] { 0x0A, 0x0C, 0x08 });
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(_recvQQ)));
            data.Write((byte) 0x10);
            data.Write(
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(MessageTime).Replace(" ", ""), 16))));
            data.Write(new byte[] { 0x20, 0x00 });
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[] { 0x08, 0x01, 0x12, 0x03, 0x98, 0x01, 0x00 });
            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

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

protected override void PutBody()
        {
            var pic = new Bitmap(FileName);
            var width = pic.Size.Width; // 图片的宽度
            var height = pic.Size.Height; // 图片的高度
            var picBytes = ImageHelper.ImageToBytes(pic);
            var md5 = QQTea.MD5(picBytes);

            var data = new BinaryWriter(new MemoryStream());
            data.Write(new byte[]
            {
                0x01, 0x08, 0x01, 0x12
            });
            data.Write((byte) 0x5A);
            data.Write((byte) 0x08);
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(User.QQ)));
            data.Write((byte) 0x10);
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(ToQQ)));
            data.BeWrite((ushort) 0x1800);
            data.Write((byte) 0x22);
            data.Write((byte) 0x10);
            data.Write(md5);
            data.Write((byte) 0x28);
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(picBytes.Length)));
            data.Write((byte) 0x32);
            data.Write((byte) 0x1A);
            data.Write(new byte[]
            {
                0x57, 0x00, 0x53, 0x00, 0x4E, 0x00, 0x53, 0x00, 0x4C, 0x00, 0x54, 0x00,
                0x31, 0x00, 0x36, 0x00, 0x47, 0x00, 0x45, 0x00, 0x4F, 0x00, 0x5B, 0x00,
                0x5F, 0x00
            });
            data.BeWrite((ushort) 0x3801);
            data.BeWrite((ushort) 0x4801);
            data.Write((byte) 0x70);
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(width)));
            data.Write((byte) 0x78);
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(height)));

            BodyWriter.Write(new byte[]
            {
                0x00, 0x00, 0x00, 0x07
            });
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[]
            {
                0x08, 0x01, 0x12, 0x03, 0x98, 0x01
            });
            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

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

protected override void PutBody()
        {
            BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x07 });
            var data = new BinaryWriter(new MemoryStream());
            data.Write(new byte[] { 0x03, 0x08, 0x03, 0x22, 0x46, 0x08 });
            data.Write(Util.HexStringToByteArray(Util.PB_toLength(_recvGroupQQ)));
            data.Write((byte) 0x10);
            data.Write(
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(MessageTime).Replace(" ", ""), 16))));
            data.Write(new byte[] { 0x20, 0x00 });
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[] { 0x08, 0x01, 0x12, 0x03, 0x98, 0x01, 0x00 });
            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

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

public static byte[] GetQdData(QQUser user)
        {
            try
            {
                var data = new BinaryWriter(new MemoryStream());
                data.Write(user.TXProtocol.DwServerIP);

                var qddata = new BinaryWriter(new MemoryStream());
                qddata.Write(user.TXProtocol.DwQdVerion);
                qddata.Write(user.TXProtocol.DwPubNo);
                qddata.BeWrite(user.QQ);
                qddata.BeWrite((ushort) data.BaseStream.Length);

                data = new BinaryWriter(new MemoryStream());
                data.Write(user.TXProtocol.QdPreFix);
                data.BeWrite(user.TXProtocol.CQdProtocolVer);
                data.BeWrite(user.TXProtocol.DwQdVerion);
                data.Write((byte) 0);
                data.BeWrite(user.TXProtocol.WQdCsCmdNo);
                data.Write(user.TXProtocol.CQdCcSubNo);
                data.Write(new byte[] { 0x0E, 0x88 }); //xrand(0xFFFF) + 1
                data.BeWrite(0); //四个0
                data.Write(user.TXProtocol.BufComputerIdEx);
                data.Write(user.TXProtocol.COsType);
                data.Write(user.TXProtocol.BIsWow64);
                data.Write(user.TXProtocol.DwPubNo);
                data.BeWrite((ushort) user.TXProtocol.DwClientVer);
                data.BeWrite(user.TXProtocol.DwDrvVersionInfo / 0x10000);
                data.BeWrite(user.TXProtocol.DwDrvVersionInfo % 0x10000);
                data.Write(user.TXProtocol.BufVersionTsSafeEditDat);
                data.Write(user.TXProtocol.BufVersionQScanEngineDll);
                data.Write((byte) 0);

                data.Write(new TeaCrypter().Encrypt(qddata.BaseStream.ToBytesArray(), user.TXProtocol.BufQdKey));

                data.Write(user.TXProtocol.QdSufFix);

                var size = data.BaseStream.Length + 3;
                qddata = new BinaryWriter(new MemoryStream());
                qddata.Write(user.TXProtocol.QdPreFix);
                qddata.Write(size);
                qddata.Write(data.BaseStream.Length);

                var result = data.BaseStream.ToBytesArray();
                user.TXProtocol.QdData = result;
                return result;
            }
            catch
            {
                return new byte[] { };
            }
        }

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

public byte[] Get_Tlv(QQUser user)
        {
            var data = new BinaryWriter(new MemoryStream());
            if (WSubVer == 0x0001)
            {
                data.BeWrite(WSubVer); //wSubVer

                data.Write((byte) 0x01);
                var thisKey = user.TXProtocol.BufComputerId;
                data.BeWrite(CRC32.CRC32Reverse(thisKey));
                data.WriteKey(thisKey);

                data.Write((byte) 0x02);
                thisKey = user.TXProtocol.BufComputerIdEx;
                data.BeWrite(CRC32.CRC32Reverse(thisKey));
                data.WriteKey(thisKey);
            }
            else
            {
                throw new Exception($"{Name} 无法识别的版本号 {WSubVer}");
            }

            FillHead(Command);
            FillBody(data.BaseStream.ToBytesArray(), data.BaseStream.Length);
            SetLength();
            return GetBuffer();
        }

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

public byte[] Get_Tlv(QQUser user)
        {
            var data = new BinaryWriter(new MemoryStream());
            if (WSubVer == 0x0001)
            {
                data.BeWrite(WSubVer); //wSubVer
                data.Write(user.TXProtocol.XxooB);
                data.Write((byte) 2);
                data.BeUshortWrite(0x0014);
                data.BeWrite(0x01010010);
                data.Write(Util.RandomKey());
                data.BeUshortWrite(0x0014);
                data.BeWrite(0x01020010);
                data.Write(Util.RandomKey());
            }
            else
            {
                throw new Exception($"{Name} 无法识别的版本号 {WSubVer}");
            }

            FillHead(Command);
            FillBody(data.BaseStream.ToBytesArray(), data.BaseStream.Length);
            SetLength();
            return GetBuffer();
        }

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

public byte[] Get_Tlv(QQUser user)
        {
            var data = new BinaryWriter(new MemoryStream());
            if (WSubVer == 0x0002)
            {
                data.BeWrite(WSubVer); //wSubVer
                var newbyte = user.TXProtocol.BufTgt;
                var flag = EncodeLoginFlag(newbyte, QQGlobal.QqexeMD5);
                data.Write(user.MD51);
                data.Write(flag);
                data.Write((byte) 0x10);
                data.BeWrite(0);
                data.BeWrite(2);
                var qddata = QdData.GetQdData(user);
                data.WriteKey(qddata);
                data.BeWrite(0);
            }
            else
            {
                throw new Exception($"{Name} 无法识别的版本号 {WSubVer}");
            }

            FillHead(Command);
            FillBody(data.BaseStream.ToBytesArray(), data.BaseStream.Length);
            SetLength();
            return GetBuffer();
        }

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

protected override void PutBody()
        {
            var pbGroupId = Util.HexStringToByteArray(Util.PB_toLength(_groupId));
            var pbMessageId =
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(_messageId).Replace(" ", ""), 16)));
            var pbMessageIndex =
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(_messageIndex).Replace(" ", ""), 16)));
            BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x07 });
            var data = new BinaryWriter(new MemoryStream());
            data.Write(new byte[] { 0x08, 0x01, 0x10, 0x00, 0x18 });
            data.Write(pbGroupId);
            data.Write(new byte[] { 0x22, 0x09, 0x08 });
            data.Write(pbMessageIndex); //消息索引
            data.Write((byte) 0x10);
            data.Write(pbMessageId); //消息Id
            var data_2A = new BinaryWriter(new MemoryStream());
            data_2A.Write(new byte[] { 0x08, 0x00 });
            var data12 = new BinaryWriter(new MemoryStream());
            data12.Write((byte) 0x08);
            data12.Write(pbMessageIndex); //消息索引
            data12.Write((byte) 0x10);
            data12.Write(new byte[] { 0x00, 0x18, 0x01, 0x20, 0x00 });
            data_2A.Write((byte) 0x12);
            data_2A.Write((byte) data12.BaseStream.Length);
            data_2A.Write(data12.BaseStream.ToBytesArray());
            data.Write((byte) 0x2a);
            data.Write((byte) data_2A.BaseStream.Length);
            data.Write(data_2A.BaseStream.ToBytesArray());
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[] { 0x08, 0x01, 0x12, 0x03, 0x98, 0x01, 0x00 });
            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

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

protected override void PutBody()
        {
            BodyWriter.Write(new byte[] { 0x00, 0x00, 0x00, 0x07 });
            var data = new BinaryWriter(new MemoryStream());
            var data_0A = new BinaryWriter(new MemoryStream());
            data_0A.Write((byte) 0x08);
            data_0A.Write(Util.HexStringToByteArray(Util.PB_toLength(User.QQ)));
            data_0A.Write((byte) 0x10);
            data_0A.Write(Util.HexStringToByteArray(Util.PB_toLength(_recvQQ)));
            data_0A.Write((byte) 0x18);
            data_0A.Write(Util.HexStringToByteArray(Util.PB_toLength(_msgSequence))); //消息包序
            data_0A.Write((byte) 0x28);
            data_0A.Write(
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(MessageTime).Replace(" ", ""), 16))));
            data_0A.Write(new byte[] { 0x30 });
            data_0A.Write(
                Util.HexStringToByteArray(
                    Util.PB_toLength(Convert.ToInt64(Util.ToHex(MessageId).Replace(" ", ""), 16)))); //消息Id
            data_0A.Write(new byte[] { 0x38, 0x01, 0x40, 0x00, 0x48, 0x00 });
            data.Write((byte) 0x0A);
            data.Write((byte) data_0A.BaseStream.Length); //length
            data.Write(data_0A.BaseStream.ToBytesArray());
            data.Write(new byte[] { 0x10, 0x01, 0x18, 0x01, 0x20, 0x00, 0x2a, 0x04, 0x08, 0x00, 0x10, 0x00 });
            //数据长度
            BodyWriter.BeWrite(data.BaseStream.Length);
            BodyWriter.Write(new byte[] { 0x08, 0x01, 0x12, 0x03, 0x98, 0x01, 0x00 });
            //数据
            BodyWriter.Write(data.BaseStream.ToBytesArray());
        }

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

[Obsolete("请使用BinaryWriter.Write(Richtext)方法。")]
        public static byte[] ConstructMessage(string message)
        {
            var bw = new BinaryWriter(new MemoryStream());
            var r = new Regex(@"([^\[]+)*(\[face\d+\.gif\])([^\[]+)*");
            if (r.IsMatch(message))
            {
                var faces = r.Matches(message);
                for (var i = 0; i < faces.Count; i++)
                {
                    var face = faces[i];
                    for (var j = 1; j < face.Groups.Count; j++)
                    {
                        var group = face.Groups[j].Value;
                        if (group.Contains("[face") && group.Contains(".gif]"))
                        {
                            var faceIndex =
                                Convert.ToByte(group.Substring(5, group.Length - group.LastIndexOf(".") - 4));
                            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 });
                        }
                        else if (!string.IsNullOrEmpty(group))
                        {
                            var groupMsg = Encoding.UTF8.GetBytes(group);
                            //普通消息
                            ConstructMessage(bw, groupMsg);
                        }
                    }
                }
            }

            return bw.BaseStream.ToBytesArray();
        }

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

[Obsolete("请使用BinaryWriter.Write(Richtext)方法。")]
        public static byte[] SendXml(byte[] compressMsg)
        {
            var bw = new BinaryWriter(new MemoryStream());
            bw.Write(Util.RandomKey(4));
            bw.Write(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x86, 0x00 });
            bw.Write(new byte[] { 0x00, 0x0C });
            bw.Write(new byte[] { 0xE5, 0xBE, 0xAE, 0xE8, 0xBD, 0xAF, 0xE9, 0x9B, 0x85, 0xE9, 0xBB, 0x91 });
            bw.Write(new byte[] { 0x00, 0x00, 0x14 });
            bw.BeWrite((ushort) (compressMsg.Length + 11));
            bw.Write((byte) 0x01);
            bw.BeWrite((ushort) (compressMsg.Length + 1));
            bw.Write((byte) 0x01);
            bw.Write(compressMsg);
            bw.Write(new byte[] { 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x4D });
            return bw.BaseStream.ToBytesArray();
        }

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 : SimpleJSON.cs
License : MIT License
Project Creator : 734843327

public override void Serialize (System.IO.BinaryWriter aWriter)
		{
			var tmp = new JSONData("");
			
			tmp.AsInt = AsInt;
			if (tmp.m_Data == this.m_Data)
			{
				aWriter.Write((byte)JSONBinaryTag.IntValue);
				aWriter.Write(AsInt);
				return;
			}
			tmp.AsFloat = AsFloat;
			if (tmp.m_Data == this.m_Data)
			{
				aWriter.Write((byte)JSONBinaryTag.FloatValue);
				aWriter.Write(AsFloat);
				return;
			}
			tmp.AsDouble = AsDouble;
			if (tmp.m_Data == this.m_Data)
			{
				aWriter.Write((byte)JSONBinaryTag.DoubleValue);
				aWriter.Write(AsDouble);
				return;
			}

			tmp.AsBool = AsBool;
			if (tmp.m_Data == this.m_Data)
			{
				aWriter.Write((byte)JSONBinaryTag.BoolValue);
				aWriter.Write(AsBool);
				return;
			}
			aWriter.Write((byte)JSONBinaryTag.Value);
			aWriter.Write(m_Data);
		}

19 View Source File : SimpleJSON.cs
License : MIT License
Project Creator : 734843327

public override void Serialize (System.IO.BinaryWriter aWriter)
		{
			aWriter.Write((byte)JSONBinaryTag.Array);
			aWriter.Write(m_List.Count);
			for(int i = 0; i < m_List.Count; i++)
			{
				m_List[i].Serialize(aWriter);
			}
		}

19 View Source File : SimpleJSON.cs
License : MIT License
Project Creator : 734843327

public override void Serialize (System.IO.BinaryWriter aWriter)
		{
			aWriter.Write((byte)JSONBinaryTag.Clreplaced);
			aWriter.Write(m_Dict.Count);
			foreach(string K in m_Dict.Keys)
			{
				aWriter.Write(K);
				m_Dict[K].Serialize(aWriter);
			}
		}

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

public void ReadData(Stream stream)
        {
            var binaryWriter = new BinaryWriter(stream);

            binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("RIFF"));

            uint filesize = (uint)(Data.Length + 36); // 36 is added for all the extra we're adding for the WAV header format
            binaryWriter.Write(filesize);

            binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("WAVE"));

            binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("fmt"));
            binaryWriter.Write((byte)0x20); // Null ending to the fmt

            binaryWriter.Write((int)0x10); // 16 ... length of all the above

            // AC audio headers start at Format Type,
            // and are usually 18 bytes, with some exceptions
            // notably objectID A000393 which is 30 bytes

            // WAV headers are always 16 bytes from Format Type to end of header,
            // so this extra data is truncated here.
            binaryWriter.Write(Header.Take(16).ToArray());

            binaryWriter.Write(System.Text.Encoding.ASCII.GetBytes("data"));
            binaryWriter.Write((uint)Data.Length);
            binaryWriter.Write(Data);
        }

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

public static void Write(this BinaryWriter writer, MovementData motion, bool header = true)
        {
            var wo = motion.WorldObject;
            var sequence = wo.Sequences;

            if (header)
            {
                writer.Write(sequence.GetNextSequence(SequenceType.ObjectMovement));

                if (motion.IsAutonomous)
                    writer.Write(sequence.GetCurrentSequence(SequenceType.ObjectServerControl));
                else
                    writer.Write(sequence.GetNextSequence(SequenceType.ObjectServerControl));

                writer.Write(Convert.ToByte(motion.IsAutonomous));
                writer.Align();
            }

            writer.Write((byte)motion.MovementType);
            writer.Write((byte)motion.MotionFlags);

            writer.Write((ushort)motion.CurrentStyle);    // send MotionStance as ushort

            switch (motion.MovementType)
            {
                case MovementType.Invalid:
                    writer.Write(motion.Invalid);
                    break;

                case MovementType.MoveToObject:
                    writer.Write(motion.MoveToObject);
                    break;

                case MovementType.MoveToPosition:
                    writer.Write(motion.MoveToPosition);
                    break;

                case MovementType.TurnToObject:
                    writer.Write(motion.TurnToObject);
                    break;

                case MovementType.TurnToHeading:
                    writer.Write(motion.TurnToHeading);
                    break;
            }
        }

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

public static void Write(this BinaryWriter writer, AllegianceData data)
        {
            // ObjectID - characterID - Character ID
            // uint - cpCached - XP gained while logged off
            // uint - cpreplacedhed - Total allegiance XP contribution
            // uint - bitfield - AllegianceIndex
            // Gender - gender - The gender of the character (for determining replacedle)
            // HeritageGroup - hg - The heritage of the character (for determining replacedle)
            // ushort - rank - The numerical rank (1 is lowest).

            // Choose valid sections by masking against bitfield
            // uint - level

            // ushort - loyalty - Character loyalty
            // ushort - leadership - Character leadership

            // Choose based on testing bitfield == 0x4 (HasAllegianceAge)
            // True:
            // uint - timeOnline
            // uint - allegianceAge
            // False: (Not found in later retail pcaps. Probably deprecated.)
            // ulong - uTimeOnline

            // string - name

            uint characterID = 0;
            uint cpCached = 0;
            uint cpreplacedhed = 0;
            var bitfield = AllegianceIndex.HasAllegianceAge | AllegianceIndex.HasPackedLevel;
            var gender = Gender.Female;
            var hg = HeritageGroup.Aluvian;
            ushort rank = 0;
            uint level = 0;
            ushort loyalty = 0;
            ushort leadership = 0;
            ulong uTimeOnline = 0;
            uint timeOnline = 0;
            uint allegianceAge = 0;
            var name = "";

            if (data.Node != null)
            {
                var node = data.Node;
                var playerGuid = node.PlayerGuid;
                var player = PlayerManager.FindByGuid(playerGuid, out var playerIsOnline);
                
                characterID = player.Guid.Full;
                cpCached = (uint)Math.Min(player.AllegianceXPCached, uint.MaxValue);
                cpreplacedhed = (uint)Math.Min(player.AllegianceXPGenerated, uint.MaxValue);

                if (playerIsOnline)
                    bitfield |= AllegianceIndex.LoggedIn;

                if (!node.IsMonarch && node.Player.ExistedBeforeAllegianceXpChanges)
                    bitfield |= AllegianceIndex.MayPreplacedupExperience;

                gender = (Gender)player.Gender;
                hg = (HeritageGroup)player.Heritage;
                rank = (ushort)node.Rank;
                level = (uint)player.Level;
                loyalty = (ushort)player.GetCurrentLoyalty();
                leadership = (ushort)player.GetCurrentLeadership();
                
                //if (!node.IsMonarch)
                //{
                // TODO: Get/set total time sworn to patron (allegianceAge) and total in-game time since swearing to patron (timeOnline)
                //}

                name = player.Name;
                
            }

            writer.Write(characterID);
            writer.Write(cpCached);
            writer.Write(cpreplacedhed);
            writer.Write((uint)bitfield);
            writer.Write((byte)gender);
            writer.Write((byte)hg);
            writer.Write(rank);

            if (bitfield.HasFlag(AllegianceIndex.HasPackedLevel))
                writer.Write(level);

            writer.Write(loyalty);
            writer.Write(leadership);

            if (bitfield.HasFlag(AllegianceIndex.HasAllegianceAge))
            {
                writer.Write(timeOnline);
                writer.Write(allegianceAge);
            }
            else
                writer.Write(uTimeOnline);

            writer.WriteString16L(name);
        }

19 View Source File : BasicBlockSerializer.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public void WriteData(ILBlock block, BinaryWriter writer)
        {
            uint offset = 0;
            SequencePoint prevSeq = null;
            uint prevOffset = 0;
            foreach(var instr in block.Content)
            {
                if(rt.dbgWriter != null && instr.IR.ILAST is ILASTExpression)
                {
                    var expr = (ILASTExpression) instr.IR.ILAST;
                    var seq = expr.CILInstr == null ? null : expr.CILInstr.SequencePoint;

                    if(seq != null && seq.StartLine != 0xfeefee && (prevSeq == null || !Equals(seq, prevSeq)))
                    {
                        if(prevSeq != null)
                        {
                            uint len = offset - prevOffset, line = (uint) prevSeq.StartLine;
                            var doc = prevSeq.Doreplacedent.Url;

                            rt.dbgWriter.AddSequencePoint(block, prevOffset, len, doc, line);
                        }
                        prevSeq = seq;
                        prevOffset = offset;
                    }
                }

                writer.Write(rt.Descriptor.Architecture.OpCodes[instr.OpCode]);
                // Leave a padding to let BasicBlockChunk fixup block exit key
                writer.Write((byte) rt.Descriptor.Random.Next());
                offset += 2;

                if(instr.Operand != null)
                    if(instr.Operand is ILRegister)
                    {
                        writer.Write(rt.Descriptor.Architecture.Registers[((ILRegister) instr.Operand).Register]);
                        offset++;
                    }
                    else if(instr.Operand is ILImmediate)
                    {
                        var value = ((ILImmediate) instr.Operand).Value;
                        if(value is int)
                        {
                            writer.Write((int) value);
                            offset += 4;
                        }
                        else if(value is uint)
                        {
                            writer.Write((uint) value);
                            offset += 4;
                        }
                        else if(value is long)
                        {
                            writer.Write((long) value);
                            offset += 8;
                        }
                        else if(value is ulong)
                        {
                            writer.Write((ulong) value);
                            offset += 8;
                        }
                        else if(value is float)
                        {
                            writer.Write((float) value);
                            offset += 4;
                        }
                        else if(value is double)
                        {
                            writer.Write((double) value);
                            offset += 8;
                        }
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }
            }

            if(prevSeq != null)
            {
                uint len = offset - prevOffset, line = (uint) prevSeq.StartLine;
                var doc = prevSeq.Doreplacedent.Url;

                rt.dbgWriter.AddSequencePoint(block, prevOffset, len, doc, line);
            }
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public static void WriteCompressedUInt(this BinaryWriter writer, uint value)
        {
            do
            {
                var b = (byte) (value & 0x7f);
                value >>= 7;
                if(value != 0)
                    b |= 0x80;
                writer.Write(b);
            } while(value != 0);
        }

19 View Source File : Pack.cs
License : Apache License 2.0
Project Creator : aequabit

public byte[] Serialize(params object[] data)
    {
        MemoryStream Stream = new MemoryStream();
        BinaryWriter Writer = new BinaryWriter(Stream, Encoding.UTF8);
        byte Current = 0;

        Writer.Write(Convert.ToByte(data.Length));

        for (int I = 0; I <= data.Length - 1; I++)
        {
            Current = Table[data[I].GetType()];
            Writer.Write(Current);

            switch (Current)
            {
                case 0:
                    Writer.Write((bool)data[I]);
                    break;
                case 1:
                    Writer.Write((byte)data[I]);
                    break;
                case 2:
                    Writer.Write(((byte[])data[I]).Length);
                    Writer.Write((byte[])data[I]);
                    break;
                case 3:
                    Writer.Write((char)data[I]);
                    break;
                case 4:
                    Writer.Write(((char[])data[I]).ToString());
                    break;
                case 5:
                    Writer.Write((decimal)data[I]);
                    break;
                case 6:
                    Writer.Write((double)data[I]);
                    break;
                case 7:
                    Writer.Write((int)data[I]);
                    break;
                case 8:
                    Writer.Write((long)data[I]);
                    break;
                case 9:
                    Writer.Write((sbyte)data[I]);
                    break;
                case 10:
                    Writer.Write((short)data[I]);
                    break;
                case 11:
                    Writer.Write((float)data[I]);
                    break;
                case 12:
                    Writer.Write((string)data[I]);
                    break;
                case 13:
                    Writer.Write((uint)data[I]);
                    break;
                case 14:
                    Writer.Write((ulong)data[I]);
                    break;
                case 15:
                    Writer.Write((ushort)data[I]);
                    break;
                case 16:
                    Writer.Write(((System.DateTime)data[I]).ToBinary());
                    break;
            }
        }

        Writer.Close();
        return Stream.ToArray();
    }

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

public void Write(BinaryWriter bw)
        {
            foreach (var entry in _entries)
            {
                entry.Write(bw);
            }

            foreach (var s in _nameTable)
            {
                byte[] nameData = Encoding.ASCII.GetBytes(s);
                bw.Write( nameData );
                bw.Write( (byte)0 );
            }
        }

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

public void ExportMultichannelAsPCM(Stream soundBankStream, Stream outStream)
        {
            int numBlocks = _fileHeader.numBlocks;
            int numChannels = _fileHeader.numChannels;
            DviAdpcmDecoder.AdpcmState[] state = new DviAdpcmDecoder.AdpcmState[numChannels];

            BinaryWriter bw = new BinaryWriter(outStream);

            int[] inverseChannelOrder = new int[numChannels];
            for (int i = 0; i < numChannels; i++)
            {
                inverseChannelOrder[_channelOrder[i]] = i;
            }

            for (int i = 0; i < numChannels; i++)
            {
                state[i] = new DviAdpcmDecoder.AdpcmState();
            }

            for (int blockIndex = 0; blockIndex < numBlocks; blockIndex++)
            {
                byte[][] blockData = new byte[numChannels][];
                
                // Decode the block for all channels
                for (int channelIndex = 0; channelIndex < numChannels; channelIndex++)
                {
                    MemoryStream ms = new MemoryStream();
                    ExportWaveBlockAsPCM(channelIndex, blockIndex, ref state[channelIndex], soundBankStream, ms);
                    blockData[channelIndex] = ms.ToArray();
                }

                // Now interleave them
                for (int j = 0; j < blockData[0].Length / 2; j++)
                {
                    for (int i = 0; i < numChannels; i++)
                    {
                        bw.Write(blockData[inverseChannelOrder[i]][j*2 + 0]);
                        bw.Write(blockData[inverseChannelOrder[i]][j*2 + 1]);
                    }
                }
            }
        }

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

private static void ExportPublicKey(RSACryptoServiceProvider csp, TextWriter outputStream)
        {
            var parameters = csp.ExportParameters(false);
            using (var stream = new MemoryStream())
            {
                var writer = new BinaryWriter(stream);
                writer.Write((byte)0x30); // SEQUENCE
                using (var innerStream = new MemoryStream())
                {
                    var innerWriter = new BinaryWriter(innerStream);
                    innerWriter.Write((byte)0x30); // SEQUENCE
                    EncodeLength(innerWriter, 13);
                    innerWriter.Write((byte)0x06); // OBJECT IDENTIFIER
                    var rsaEncryptionOid = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
                    EncodeLength(innerWriter, rsaEncryptionOid.Length);
                    innerWriter.Write(rsaEncryptionOid);
                    innerWriter.Write((byte)0x05); // NULL
                    EncodeLength(innerWriter, 0);
                    innerWriter.Write((byte)0x03); // BIT STRING
                    using (var bitStringStream = new MemoryStream())
                    {
                        var bitStringWriter = new BinaryWriter(bitStringStream);
                        bitStringWriter.Write((byte)0x00); // # of unused bits
                        bitStringWriter.Write((byte)0x30); // SEQUENCE
                        using (var paramsStream = new MemoryStream())
                        {
                            var paramsWriter = new BinaryWriter(paramsStream);
                            EncodeIntegerBigEndian(paramsWriter, parameters.Modulus); // Modulus
                            EncodeIntegerBigEndian(paramsWriter, parameters.Exponent); // Exponent
                            var paramsLength = (int)paramsStream.Length;
                            EncodeLength(bitStringWriter, paramsLength);
                            bitStringWriter.Write(paramsStream.GetBuffer(), 0, paramsLength);
                        }
                        var bitStringLength = (int)bitStringStream.Length;
                        EncodeLength(innerWriter, bitStringLength);
                        innerWriter.Write(bitStringStream.GetBuffer(), 0, bitStringLength);
                    }
                    var length = (int)innerStream.Length;
                    EncodeLength(writer, length);
                    writer.Write(innerStream.GetBuffer(), 0, length);
                }

                var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
                outputStream.WriteLine("-----BEGIN PUBLIC KEY-----");
                for (var i = 0; i < base64.Length; i += 64)
                {
                    outputStream.WriteLine(base64, i, Math.Min(64, base64.Length - i));
                }
                outputStream.WriteLine("-----END PUBLIC KEY-----");
            }
        }

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

private static void EncodeIntegerBigEndian(BinaryWriter stream, byte[] value, bool forceUnsigned = true)
        {
            stream.Write((byte)0x02); // INTEGER
            var prefixZeros = 0;
            for (var i = 0; i < value.Length; i++)
            {
                if (value[i] != 0) break;
                prefixZeros++;
            }
            if (value.Length - prefixZeros == 0)
            {
                EncodeLength(stream, 1);
                stream.Write((byte)0);
            }
            else
            {
                if (forceUnsigned && value[prefixZeros] > 0x7f)
                {
                    // Add a prefix zero to force unsigned if the MSB is 1
                    EncodeLength(stream, value.Length - prefixZeros + 1);
                    stream.Write((byte)0);
                }
                else
                {
                    EncodeLength(stream, value.Length - prefixZeros);
                }
                for (var i = prefixZeros; i < value.Length; i++)
                {
                    stream.Write(value[i]);
                }
            }
        }

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

private static void EncodeLength(BinaryWriter stream, int length)
        {
            if (length < 0) throw new ArgumentOutOfRangeException("length", "Length must be non-negative");
            if (length < 0x80)
            {
                // Short form
                stream.Write((byte)length);
            }
            else
            {
                // Long form
                var temp = length;
                var bytesRequired = 0;
                while (temp > 0)
                {
                    temp >>= 8;
                    bytesRequired++;
                }
                stream.Write((byte)(bytesRequired | 0x80));
                for (var i = bytesRequired - 1; i >= 0; i--)
                {
                    stream.Write((byte)(length >> (8 * i) & 0xff));
                }
            }
        }

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

private void WriteTokenInternal(BsonToken t)
        {
            switch (t.Type)
            {
                case BsonType.Object:
                {
                    BsonObject value = (BsonObject)t;
                    _writer.Write(value.CalculatedSize);
                    foreach (BsonProperty property in value)
                    {
                        _writer.Write((sbyte)property.Value.Type);
                        WriteString((string)property.Name.Value, property.Name.ByteCount, null);
                        WriteTokenInternal(property.Value);
                    }
                    _writer.Write((byte)0);
                }
                    break;
                case BsonType.Array:
                {
                    BsonArray value = (BsonArray)t;
                    _writer.Write(value.CalculatedSize);
                    ulong index = 0;
                    foreach (BsonToken c in value)
                    {
                        _writer.Write((sbyte)c.Type);
                        WriteString(index.ToString(CultureInfo.InvariantCulture), MathUtils.IntLength(index), null);
                        WriteTokenInternal(c);
                        index++;
                    }
                    _writer.Write((byte)0);
                }
                    break;
                case BsonType.Integer:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture));
                }
                    break;
                case BsonType.Long:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write(Convert.ToInt64(value.Value, CultureInfo.InvariantCulture));
                }
                    break;
                case BsonType.Number:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
                }
                    break;
                case BsonType.String:
                {
                    BsonString value = (BsonString)t;
                    WriteString((string)value.Value, value.ByteCount, value.CalculatedSize - 4);
                }
                    break;
                case BsonType.Boolean:
                {
                    BsonValue value = (BsonValue)t;
                    _writer.Write((bool)value.Value);
                }
                    break;
                case BsonType.Null:
                case BsonType.Undefined:
                    break;
                case BsonType.Date:
                {
                    BsonValue value = (BsonValue)t;

                    long ticks = 0;

                    if (value.Value is DateTime)
                    {
                        DateTime dateTime = (DateTime)value.Value;
                        if (DateTimeKindHandling == DateTimeKind.Utc)
                        {
                            dateTime = dateTime.ToUniversalTime();
                        }
                        else if (DateTimeKindHandling == DateTimeKind.Local)
                        {
                            dateTime = dateTime.ToLocalTime();
                        }

                        ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false);
                    }
#if !NET20
                    else
                    {
                        DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value;
                        ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset);
                    }
#endif

                    _writer.Write(ticks);
                }
                    break;
                case BsonType.Binary:
                {
                    BsonBinary value = (BsonBinary)t;

                    byte[] data = (byte[])value.Value;
                    _writer.Write(data.Length);
                    _writer.Write((byte)value.BinaryType);
                    _writer.Write(data);
                }
                    break;
                case BsonType.Oid:
                {
                    BsonValue value = (BsonValue)t;

                    byte[] data = (byte[])value.Value;
                    _writer.Write(data);
                }
                    break;
                case BsonType.Regex:
                {
                    BsonRegex value = (BsonRegex)t;

                    WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null);
                    WriteString((string)value.Options.Value, value.Options.ByteCount, null);
                }
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
            }
        }

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

private void WriteString(string s, int byteCount, int? calculatedlengthPrefix)
        {
            if (calculatedlengthPrefix != null)
            {
                _writer.Write(calculatedlengthPrefix.GetValueOrDefault());
            }

            WriteUtf8Bytes(s, byteCount);

            _writer.Write((byte)0);
        }

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

public void Write(BinaryWriter bw) {
        Header.Write(bw);
        int stride = Header.Width << 2;
        for (int i = (Header.Height >> 1) - 1; i >= 0; i--)
          bw.Write(Colors, i * stride, stride);
        for (int i = 0; i < 2 * MaskSize; i++)
          bw.Write((byte)0);        
      }

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

public void Write(BinaryWriter bw) {
        bw.Write(Width);
        bw.Write(Height);
        bw.Write(ColorCount);
        bw.Write(Reserved);
        bw.Write(Planes);
        bw.Write(BitCount);
        bw.Write(BytesInRes);
        bw.Write(ImageOffset);
      }

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

public static OxyImage FromArgb(int width, int height, byte[] pixelData, int dpi = 96)
        {
            var ms = new MemoryStream();
            var w = new BinaryWriter(ms);

            const int OffBits = 14 + 108;
            var size = OffBits + pixelData.Length;

            // Bitmap file header (14 bytes)
            w.Write((byte)'B');
            w.Write((byte)'M');
            w.Write((uint)size);
            w.Write((ushort)0);
            w.Write((ushort)0);
            w.Write((uint)OffBits);

            // Bitmap V4 info header (108 bytes)
            WriteBitmapV4Header(w, width, height, 32, pixelData.Length, dpi);

            // Pixel array (from bottom-left corner)
            w.Write(pixelData);

            return new OxyImage(ms.ToArray());
        }

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

public static OxyImage FromIndexed8(
            int width, int height, byte[] indexedPixelData, OxyColor[] palette, int dpi = 96)
        {
            if (indexedPixelData.Length != width * height)
            {
                throw new ArgumentException("Length of data is not correct.", "indexedPixelData");
            }

            if (palette.Length == 0)
            {
                throw new ArgumentException("Palette not defined.", "palette");
            }

            var ms = new MemoryStream();
            var w = new BinaryWriter(ms);

            var offBits = 14 + 40 + (4 * palette.Length);
            var size = offBits + indexedPixelData.Length;

            // Bitmap file header (14 bytes)
            w.Write((byte)'B');
            w.Write((byte)'M');
            w.Write((uint)size);
            w.Write((ushort)0);
            w.Write((ushort)0);
            w.Write((uint)offBits);

            // Bitmap info header
            WriteBitmapInfoHeader(w, width, height, 8, indexedPixelData.Length, dpi, palette.Length);

            // Color table
            foreach (var color in palette)
            {
                w.Write(color.B);
                w.Write(color.G);
                w.Write(color.R);
                w.Write(color.A);
            }

            // Pixel array (from bottom-left corner)
            w.Write(indexedPixelData);

            return new OxyImage(ms.ToArray());
        }

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

public static OxyImage FromArgbX(int width, int height, byte[] pixelData, int dpi = 96)
        {
            var ms = new MemoryStream();
            var w = new BinaryWriter(ms);

            const int OffBits = 14 + 40;
            var size = OffBits + pixelData.Length;

            // Bitmap file header (14 bytes)
            w.Write((byte)'B');
            w.Write((byte)'M');
            w.Write((uint)size);
            w.Write((ushort)0);
            w.Write((ushort)0);
            w.Write((uint)OffBits);

            // Bitmap info header
            WriteBitmapInfoHeader(w, width, height, 32, pixelData.Length, dpi);

            // Pixel array (from bottom-left corner)
            w.Write(pixelData);

            return new OxyImage(ms.ToArray());
        }

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

public static byte[] Encode(OxyColor[,] pixels, int dpi = 96)
        {
            int height = pixels.GetLength(0);
            int width = pixels.GetLength(1);
            var bytes = new byte[(width * height * 4) + height];

            int k = 0;
            for (int i = height - 1; i >= 0; i--)
            {
                bytes[k++] = 0; // Filter
                for (int j = 0; j < width; j++)
                {
                    bytes[k++] = pixels[i, j].R;
                    bytes[k++] = pixels[i, j].G;
                    bytes[k++] = pixels[i, j].B;
                    bytes[k++] = pixels[i, j].A;
                }
            }

            var w = new MemoryWriter();
            w.Write((byte)0x89);
            w.Write("PNG\r\n\x1a\n".ToCharArray());
            WriteChunk(w, "IHDR", CreateHeaderData(width, height));
            WriteChunk(w, "pHYs", CreatePhysicalDimensionsData(dpi, dpi));
            WriteChunk(w, "IDAT", CreateUncompressedBlocks(bytes));
            WriteChunk(w, "IEND", new byte[0]);
            return w.ToArray();
        }

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

private static byte[] CreateHeaderData(int width, int height)
        {
            // http://www.w3.org/TR/PNG-Chunks.html
            var w = new MemoryWriter();
            WriteBigEndian(w, width);
            WriteBigEndian(w, height);
            w.Write((byte)8); // bit depth
            w.Write((byte)6); // color type RGBA
            w.Write((byte)0); // compression method
            w.Write((byte)0); // filter method
            w.Write((byte)0); // interlace method
            return w.ToArray();
        }

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

private static byte[] CreatePhysicalDimensionsData(int dpix, int dpiy)
        {
            var ppux = (int)(dpix / 0.0254);
            var ppuy = (int)(dpiy / 0.0254);
            var w = new MemoryWriter();
            WriteBigEndian(w, ppux);
            WriteBigEndian(w, ppuy);
            w.Write((byte)1); // Unit: metre
            return w.ToArray();
        }

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

private static byte[] CreateUncompressedBlocks(byte[] bytes)
        {
            // http://www.w3.org/TR/PNG-Compression.html
            const int MaxDeflate = 0xFFFF;
            var w = new MemoryWriter();
            const uint CompressionMethod = 8;
            const uint Check = (31 - ((CompressionMethod << 8) % 31)) % 31;
            w.Write((byte)CompressionMethod);
            w.Write((byte)Check);
            for (int i = 0; i < bytes.Length; i += MaxDeflate)
            {
                var n = (ushort)Math.Min(bytes.Length - i, MaxDeflate);
                var last = (byte)(i + n < bytes.Length ? 0 : 1);
                w.Write(last);
                w.Write((byte)(n & 0xFF));
                w.Write((byte)((n >> 8) & 0xFF));
                var n2 = ~n;
                w.Write((byte)(n2 & 0xFF));
                w.Write((byte)((n2 >> 8) & 0xFF));
                w.Write(bytes, i, n);
            }

            WriteBigEndian(w, Adler32(bytes));
            return w.ToArray();
        }

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

private static void WriteBigEndian(BinaryWriter w, int value)
        {
            var bytes = BitConverter.GetBytes(value);
            w.Write(bytes[3]);
            w.Write(bytes[2]);
            w.Write(bytes[1]);
            w.Write(bytes[0]);
        }

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

private static void WriteBigEndian(BinaryWriter w, uint value)
        {
            var bytes = BitConverter.GetBytes(value);
            w.Write(bytes[3]);
            w.Write(bytes[2]);
            w.Write(bytes[1]);
            w.Write(bytes[0]);
        }

19 View Source File : VectorTests.cs
License : MIT License
Project Creator : allisterb

private void WriteMandelbrotPPM(int[] output, string name)
        {

            using (StreamWriter sw = new StreamWriter(name))
            {
                sw.Write("P6\n");
                sw.Write(string.Format("{0} {1}\n", Mandelbrot_Width, Mandelbrot_Height));
                sw.Write("255\n");
                sw.Close();
            }
            using (BinaryWriter bw = new BinaryWriter(new FileStream(name, FileMode.Append)))
            {
                for (int i = 0; i < Mandelbrot_Width * Mandelbrot_Height; i++)
                {
                    byte b = output[i] == 256 ? (byte) 20 : (byte) 240;
                    bw.Write(b);
                    bw.Write(b);
                    bw.Write(b);
                }
            }
            
        }

19 View Source File : VectorTests.cs
License : MIT License
Project Creator : allisterb

private void WriteMandelbrotPPM(byte[] output, string name)
        {

            using (StreamWriter sw = new StreamWriter(name))
            {
                sw.Write("P6\n");
                sw.Write(string.Format("{0} {1}\n", Mandelbrot_Width, Mandelbrot_Height));
                sw.Write("255\n");
                sw.Close();
            }
            using (BinaryWriter bw = new BinaryWriter(new FileStream(name, FileMode.Append)))
            {
                for (int i = 0; i < Mandelbrot_Width * Mandelbrot_Height; i++)
                {
                    byte b = output[i] == 255 ? (byte)20 : (byte)240;
                    bw.Write(b);
                    bw.Write(b);
                    bw.Write(b);
                }
            }

        }

See More Examples