Here are the examples of the csharp api System.IO.BinaryReader.ReadUInt16() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1353 Examples
19
Source : ShaderParamTexture.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public new void Read(BinaryReader br)
{
base.Read(br);
Unknown1 = br.ReadUInt32();
Unknown2 = br.ReadUInt16();
Unknown3 = br.ReadUInt16();
Unknown4 = br.ReadUInt32();
Unknown5 = br.ReadUInt32();
TextureNameOffset = ResourceUtil.ReadOffset(br);
Unknown7 = br.ReadUInt32();
br.BaseStream.Seek(TextureNameOffset, SeekOrigin.Begin);
TextureName = ResourceUtil.ReadNullTerminatedString(br);
}
19
Source : CompressionLZXCodec.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Decompress(Stream source, Stream destination)
{
var br = new BinaryReader(source);
if (br.ReadUInt16() != 0xEF12)
{
throw new Exception("Unexpected input in compressed resource file.");
}
throw new NotImplementedException();
/*
// The following code requires code that is is ommitted due to licensing issues.
var length = DataUtil.SwapEndian(br.ReadUInt32());
var decompressor = new LZXDecompressor();
decompressor.Initialize(17);
uint bytesRead = 0;
while (bytesRead < length)
{
uint inChunkSize, outChunkSize;
inChunkSize = br.ReadByte();
if (inChunkSize != 0xFF)
{
inChunkSize <<= 8;
inChunkSize |= br.ReadByte();
outChunkSize = 0x8000;
bytesRead += 2;
}
else
{
outChunkSize = ((uint) br.ReadByte() << 8) | (br.ReadByte());
inChunkSize = ((uint) br.ReadByte() << 8) | (br.ReadByte());
bytesRead += 5;
}
byte[] inData = br.ReadBytes((int) inChunkSize);
var outData = new byte[outChunkSize];
bytesRead += inChunkSize;
try
{
decompressor.Decompress(inData, outData, (int) inChunkSize, (int) outChunkSize);
}
catch
{
throw new Exception("Could not decompress resource.");
}
destination.Write(outData, 0, (int) outChunkSize);
}
*/
}
19
Source : VertexDeclaration.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Read(BinaryReader br)
{
UsageFlags = br.ReadUInt32();
Stride = br.ReadUInt16();
AlterateDecoder = br.ReadByte();
Type = br.ReadByte();
DeclarationTypes = br.ReadUInt64();
}
19
Source : Shader.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public new void Read(BinaryReader br)
{
base.Read(br);
Unknown1 = br.ReadUInt16();
Unknown2 = br.ReadByte();
Unknown3 = br.ReadByte();
Unknown4 = br.ReadUInt16();
Unknown4_1 = br.ReadUInt16();
Unknown5 = br.ReadUInt32();
var shaderParamOffsetsOffset = ResourceUtil.ReadOffset(br);
Unknown6 = br.ReadUInt32();
ShaderParamCount = br.ReadInt32();
Unknown8 = br.ReadUInt32();
var shaderParamTypesOffset = ResourceUtil.ReadOffset(br);
Hash = br.ReadUInt32();
Unknown9 = br.ReadUInt32();
Unknown10 = br.ReadUInt32();
var shaderParamNameOffset = ResourceUtil.ReadOffset(br);
Unknown11 = br.ReadUInt32();
Unknown12 = br.ReadUInt32();
Unknown13 = br.ReadUInt32();
// Data :
using (new StreamContext(br))
{
br.BaseStream.Seek(shaderParamOffsetsOffset, SeekOrigin.Begin);
ShaderParamOffsets = new SimpleArray<uint>(br, ShaderParamCount, ResourceUtil.ReadOffset);
br.BaseStream.Seek(shaderParamTypesOffset, SeekOrigin.Begin);
ShaderParamTypes = new SimpleArray<byte>(br, ShaderParamCount, r => r.ReadByte());
br.BaseStream.Seek(shaderParamNameOffset, SeekOrigin.Begin);
ShaderParamNames = new SimpleArray<uint>(br, ShaderParamCount, r => r.ReadUInt32());
ShaderParams = new Dictionary<ParamNameHash, IShaderParam>(ShaderParamCount);
for (int i = 0; i < ShaderParamCount; i++)
{
try
{
var obj = ParamObjectFactory.Create((ParamType) ShaderParamTypes[i]);
br.BaseStream.Seek(ShaderParamOffsets[i], SeekOrigin.Begin);
obj.Read(br);
ShaderParams.Add((ParamNameHash) ShaderParamNames[i], obj);
}
catch
{
ShaderParams.Add((ParamNameHash) ShaderParamNames[i], null);
}
}
}
}
19
Source : ChannelInfo.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Read(BinaryReader br)
{
unk1Reserved = br.ReadInt32();
unk2Reserved = br.ReadInt32();
hash = br.ReadUInt32();
numSamplesInBytes = br.ReadInt32();
numSamples16Bit = br.ReadInt32();
unk4 = br.ReadInt32();
sampleRate = br.ReadUInt16();
unk5 = br.ReadInt16();
unk6 = br.ReadInt16();
unk7Reserved = br.ReadInt16();
offsetAdpcmStateTable = br.ReadInt64();
}
19
Source : Skeleton.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Read(BinaryReader br)
{
uint bonesOffset = ResourceUtil.ReadOffset(br);
uint unknownIntsOffset = ResourceUtil.ReadOffset(br);
uint transforms1Offset = ResourceUtil.ReadOffset(br);
uint transforms2Offset = ResourceUtil.ReadOffset(br);
uint transforms3Offset = ResourceUtil.ReadOffset(br);
BoneCount = br.ReadUInt16();
Unknown0 = br.ReadInt16();
Unknown1 = br.ReadInt32();
Unknown2 = br.ReadInt32();
BoneIDMappings = new SimpleCollection<BoneIDMapping>(br, r => new BoneIDMapping(r));
Unknown3 = br.ReadInt32();
UnknownHash = br.ReadUInt32();
Unknown4 = br.ReadInt32();
UnknownSubStruct = new SubStruct(br);
// Data:
br.BaseStream.Seek(bonesOffset, SeekOrigin.Begin);
Bones = new SimpleArray<Bone>(br, BoneCount, r => new Bone(r));
br.BaseStream.Seek(unknownIntsOffset, SeekOrigin.Begin);
UnknownInts = new SimpleArray<int>(br, BoneCount, r => r.ReadInt32());
br.BaseStream.Seek(transforms1Offset, SeekOrigin.Begin);
Transforms1 = new SimpleArray<Matrix44>(br, BoneCount, r => new Matrix44(r));
br.BaseStream.Seek(transforms2Offset, SeekOrigin.Begin);
Transforms2 = new SimpleArray<Matrix44>(br, BoneCount, r => new Matrix44(r));
br.BaseStream.Seek(transforms3Offset, SeekOrigin.Begin);
Transforms3 = new SimpleArray<Matrix44>(br, BoneCount, r => new Matrix44(r));
// Fun stuff...
// Build a mapping of Offset -> Bone
var boneOffsetMapping = new Dictionary<uint, Bone>();
boneOffsetMapping.Add(0, null);
foreach (var bone in Bones)
{
boneOffsetMapping.Add((uint)bone.Offset, bone);
}
// Now resolve all the bone offsets to the real bones
foreach (var bone in Bones)
{
bone.Parent = boneOffsetMapping[bone.ParentOffset];
bone.FirstChild = boneOffsetMapping[bone.FirstChildOffset];
bone.NextSibling = boneOffsetMapping[bone.NextSiblingOffset];
}
}
19
Source : TextureInfo.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Read(BinaryReader br)
{
// Full structure of rage::grcTexturePC
// rage::datBase
VTable = br.ReadUInt32();
// rage::pgBase
BlockMapOffset = ResourceUtil.ReadOffset(br);
// Texture Info struct:
Unknown1 = br.ReadUInt32(); // BYTE, BYTE, WORD
Unknown2 = br.ReadUInt32();
Unknown3 = br.ReadUInt32();
uint nameOffset = ResourceUtil.ReadOffset(br);
Unknown4 = br.ReadUInt32();
// Texture Data struct:
Width = br.ReadUInt16();
Height = br.ReadUInt16();
Format = (D3DFormat) br.ReadInt32();
StrideSize = br.ReadUInt16();
Type = br.ReadByte();
Levels = br.ReadByte();
UnknownFloat1 = br.ReadSingle();
UnknownFloat2 = br.ReadSingle();
UnknownFloat3 = br.ReadSingle();
UnknownFloat4 = br.ReadSingle();
UnknownFloat5 = br.ReadSingle();
UnknownFloat6 = br.ReadSingle();
PrevTextureInfoOffset = ResourceUtil.ReadOffset(br);
NextTextureInfoOffset = ResourceUtil.ReadOffset(br);
RawDataOffset = ResourceUtil.ReadDataOffset(br);
Unknown6 = br.ReadUInt32();
// Read texture name
br.BaseStream.Seek(nameOffset, SeekOrigin.Begin);
Name = ResourceUtil.ReadNullTerminatedString(br);
}
19
Source : WaveInfo.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Read(BinaryReader br)
{
offset = br.ReadInt64();
hash = br.ReadUInt32();
numSamplesInBytes = br.ReadInt32();
numSamplesInBytes_computed = SoundBankMono.GetPaddedSize(numSamplesInBytes);
numSamples16Bit = br.ReadInt32();
unk5 = br.ReadInt32();
samplerate = br.ReadUInt16();
unk6 = br.ReadUInt16();
if (Header.size > 32)
{
unk7 = br.ReadInt32();
offsetToStates = br.ReadInt64();
numSamples16Bit2 = br.ReadUInt32();
unk11 = br.ReadUInt32();
unk12 = br.ReadUInt32();
numStates = br.ReadInt32();
if (numStates > 0)
{
is_compressed = true;
states = new DviAdpcmDecoder.AdpcmState[numStates];
for (int j = 0; j < numStates; j++)
{
DviAdpcmDecoder.AdpcmState state = new DviAdpcmDecoder.AdpcmState();
state.valprev = br.ReadInt16();
state.index = br.ReadByte();
states[j] = state;
}
}
}
}
19
Source : TextureInfo.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
public void Read(BinaryReader br)
{
VTable = br.ReadUInt32();
Unknown1 = br.ReadUInt32();
Unknown2 = br.ReadUInt16();
Unknown3 = br.ReadUInt16();
Unknown4 = br.ReadUInt32();
Unknown5 = br.ReadUInt32();
TextureNameOffset = ResourceUtil.ReadOffset(br);
Unknown7 = br.ReadUInt32();
br.BaseStream.Seek(TextureNameOffset, SeekOrigin.Begin);
TextureName = ResourceUtil.ReadNullTerminatedString(br);
}
19
Source : UInt16Data.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
public override void Read(BinaryReader reader) {
Value = reader.ReadUInt16();
}
19
Source : ImageTool.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public ImageFormat GetFormat()
{
if (this._ifcache != ImageFormat.Unknown)
return this._ifcache;
using (var br = new BinaryReader(this.SourceStream, Utilities.UTF8, true))
{
var bgn64 = br.ReadUInt64();
if (bgn64 == PNG_MAGIC)
return this._ifcache = ImageFormat.Png;
bgn64 &= GIF_MASK;
if (bgn64 == GIF_MAGIC_1 || bgn64 == GIF_MAGIC_2)
return this._ifcache = ImageFormat.Gif;
var bgn32 = (uint)(bgn64 & MASK32);
if (bgn32 == WEBP_MAGIC_1 && br.ReadUInt32() == WEBP_MAGIC_2)
return this._ifcache = ImageFormat.WebP;
var bgn16 = (ushort)(bgn32 & MASK16);
if (bgn16 == JPEG_MAGIC_1)
{
this.SourceStream.Seek(-2, SeekOrigin.End);
if (br.ReadUInt16() == JPEG_MAGIC_2)
return this._ifcache = ImageFormat.Jpeg;
}
}
throw new InvalidDataException("The data within the stream was not valid image data.");
}
19
Source : StlFileImporter.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
public static Mesh[] ReadBinary( byte[] bytes,
float normalSmoothAngleThreshold )
{
// Specification from https://en.wikipedia.org/wiki/STL_(file_format).
// -------------------------------------------------------------------
// UINT8[80] – Header
// UINT32 – Number of triangles
//
// foreach triangle
// REAL32[3] – Normal vector
// REAL32[3] – Vertex 1
// REAL32[3] – Vertex 2
// REAL32[3] – Vertex 3
// UINT16 – Attribute byte count
// end
// -------------------------------------------------------------------
var meshes = new List<Mesh>();
using ( var memStream = new MemoryStream( bytes ) )
using ( var binStream = new BinaryReader( memStream ) ) {
binStream.ReadBytes( 80 );
int numTriangles = (int)binStream.ReadUInt32();
var meshData = new MeshData( 3 * numTriangles, normalSmoothAngleThreshold );
var vertexBuffer = new Vector3[ 3 ];
for ( int globalTriangleNumber = 0; globalTriangleNumber < numTriangles; ++globalTriangleNumber ) {
var normal = binStream.ReadVector3().ToLeftHanded();
for ( int triangleVertexIndex = 0; triangleVertexIndex < 3; ++triangleVertexIndex )
vertexBuffer[ triangleVertexIndex ] = binStream.ReadVector3().ToLeftHanded();
meshData.Add( normal, vertexBuffer );
// TODO STL: Parse color if bit index 15 is set (or not in some implementations) ("hack").
binStream.ReadUInt16();
if ( meshData.Vertices.Count >= ushort.MaxValue - 3 )
meshes.Add( (Mesh)meshData );
}
if ( meshData.IsValid )
meshes.Add( (Mesh)meshData );
}
return meshes.ToArray();
}
19
Source : RSAEncryptor.cs
with Apache License 2.0
from alipay
with Apache License 2.0
from alipay
private static RSACryptoServiceProvider BuildRSAServiceProvider(byte[] privateKey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;
byte bt = 0;
ushort twobytes = 0;
int elems = 0;
//set up stream to decode the asn.1 encoded RSA private key
//wrap Memory Stream with BinaryReader for easy reading
using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(privateKey)))
{
twobytes = binaryReader.ReadUInt16();
//data read as little endian order (actual data order for Sequence is 30 81)
if (twobytes == 0x8130)
{
//advance 1 byte
binaryReader.ReadByte();
}
else if (twobytes == 0x8230)
{
//advance 2 bytes
binaryReader.ReadInt16();
}
else
{
return null;
}
twobytes = binaryReader.ReadUInt16();
//version number
if (twobytes != 0x0102)
{
return null;
}
bt = binaryReader.ReadByte();
if (bt != 0x00)
{
return null;
}
//all private key components are Integer sequences
elems = GetIntegerSize(binaryReader);
MODULUS = binaryReader.ReadBytes(elems);
elems = GetIntegerSize(binaryReader);
E = binaryReader.ReadBytes(elems);
elems = GetIntegerSize(binaryReader);
D = binaryReader.ReadBytes(elems);
elems = GetIntegerSize(binaryReader);
P = binaryReader.ReadBytes(elems);
elems = GetIntegerSize(binaryReader);
Q = binaryReader.ReadBytes(elems);
elems = GetIntegerSize(binaryReader);
DP = binaryReader.ReadBytes(elems);
elems = GetIntegerSize(binaryReader);
DQ = binaryReader.ReadBytes(elems);
elems = GetIntegerSize(binaryReader);
IQ = binaryReader.ReadBytes(elems);
//create RSACryptoServiceProvider instance and initialize with public key
RSACryptoServiceProvider rsaService = new RSACryptoServiceProvider();
RSAParameters rsaParams = new RSAParameters
{
Modulus = MODULUS,
Exponent = E,
D = D,
P = P,
Q = Q,
DP = DP,
DQ = DQ,
InverseQ = IQ
};
rsaService.ImportParameters(rsaParams);
return rsaService;
}
}
19
Source : WaveFormat.cs
with MIT License
from amerkoleci
with MIT License
from amerkoleci
private void ReadWaveFormat(BinaryReader br, int formatChunkLength)
{
if (formatChunkLength < 16)
throw new InvalidDataException("Invalid WaveFormat Structure");
waveFormatTag = (WaveFormatEncoding)br.ReadUInt16();
channels = br.ReadInt16();
sampleRate = br.ReadInt32();
averageBytesPerSecond = br.ReadInt32();
blockAlign = br.ReadInt16();
bitsPerSample = br.ReadInt16();
if (formatChunkLength > 16)
{
extraSize = br.ReadInt16();
if (extraSize != formatChunkLength - 18)
{
Debug.WriteLine("Format chunk mismatch");
extraSize = (short)(formatChunkLength - 18);
}
}
}
19
Source : RSAHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
private RSA CreateRsaProviderFromPrivateKey(string privateKey)
{
var privateKeyBits = Convert.FromBase64String(privateKey);
var rsa = RSA.Create();
var rsaParameters = new RSAParameters();
using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
{
byte bt = 0;
ushort twobytes = 0;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130)
binr.ReadByte();
else if (twobytes == 0x8230)
binr.ReadInt16();
else
throw new Exception("Unexpected value read binr.ReadUInt16()");
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102)
throw new Exception("Unexpected version");
bt = binr.ReadByte();
if (bt != 0x00)
throw new Exception("Unexpected value read binr.ReadByte()");
rsaParameters.Modulus = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.Exponent = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.D = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.P = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.Q = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.DP = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.DQ = binr.ReadBytes(GetIntegerSize(binr));
rsaParameters.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
}
rsa.ImportParameters(rsaParameters);
return rsa;
}
19
Source : RSAHelper.cs
with Apache License 2.0
from anjoy8
with Apache License 2.0
from anjoy8
public RSA CreateRsaProviderFromPublicKey(string publicKeyString)
{
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] seq = new byte[15];
var x509Key = Convert.FromBase64String(publicKeyString);
// --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
using (MemoryStream mem = new MemoryStream(x509Key))
{
using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading
{
byte bt = 0;
ushort twobytes = 0;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareBytearrays(seq, seqOid)) //make sure Sequence for OID is correct
return null;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8203)
binr.ReadInt16(); //advance 2 bytes
else
return null;
bt = binr.ReadByte();
if (bt != 0x00) //expect null byte next
return null;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
byte lowbyte = 0x00;
byte highbyte = 0x00;
if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
else if (twobytes == 0x8202)
{
highbyte = binr.ReadByte(); //advance 2 bytes
lowbyte = binr.ReadByte();
}
else
return null;
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
int modsize = BitConverter.ToInt32(modint, 0);
int firstbyte = binr.PeekChar();
if (firstbyte == 0x00)
{ //if first byte (highest order) of modulus is zero, don't include it
binr.ReadByte(); //skip this null byte
modsize -= 1; //reduce modulus buffer size by 1
}
byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes
if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
return null;
int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
byte[] exponent = binr.ReadBytes(expbytes);
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
var rsa = RSA.Create();
RSAParameters rsaKeyInfo = new RSAParameters
{
Modulus = modulus,
Exponent = exponent
};
rsa.ImportParameters(rsaKeyInfo);
return rsa;
}
}
}
19
Source : WADReader.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public static void LoadTextureSet(string sourcename, Stream texturedata, ref List<ImageData> images, PatchNames pnames)
{
BinaryReader reader = new BinaryReader(texturedata);
int flags, width, height, patches, px, py, pi;
uint numtextures;
byte scalebytex, scalebytey;
float scalex, scaley, defaultscale;
byte[] namebytes;
TextureImage image = null;
bool strifedata;
if(texturedata.Length == 0)
return;
// Determine default scale
defaultscale = General.Map.Config.DefaultTextureScale;
// Get number of textures
texturedata.Seek(0, SeekOrigin.Begin);
numtextures = reader.ReadUInt32();
// Skip offset bytes (we will read all textures sequentially)
texturedata.Seek(4 * numtextures, SeekOrigin.Current);
// Go for all textures defined in this lump
for(uint i = 0; i < numtextures; i++)
{
// Read texture properties
namebytes = reader.ReadBytes(8);
flags = reader.ReadUInt16();
scalebytex = reader.ReadByte();
scalebytey = reader.ReadByte();
width = reader.ReadInt16();
height = reader.ReadInt16();
patches = reader.ReadInt16();
// Check for doom or strife data format
if(patches == 0)
{
// Ignore 2 bytes and then read number of patches
texturedata.Seek(2, SeekOrigin.Current);
patches = reader.ReadInt16();
strifedata = false;
}
else
{
// Texture data is in strife format
strifedata = true;
}
// Determine actual scales
if(scalebytex == 0) scalex = defaultscale; else scalex = 1f / ((float)scalebytex / 8f);
if(scalebytey == 0) scaley = defaultscale; else scaley = 1f / ((float)scalebytey / 8f);
// Validate data
if((width > 0) && (height > 0) && (patches > 0) &&
(scalex != 0) || (scaley != 0))
{
string texname = Lump.MakeNormalName(namebytes, WAD.ENCODING);
if(texname.Length > 0)
{
// Make the image object
image = new TextureImage(Lump.MakeNormalName(namebytes, WAD.ENCODING),
width, height, scalex, scaley);
}
else
{
// Can't load image without name
General.ErrorLogger.Add(ErrorType.Error, "Can't load an unnamed texture from \"" + sourcename + "\". Please consider giving names to your resources.");
}
// Go for all patches in texture
for(int p = 0; p < patches; p++)
{
// Read patch properties
px = reader.ReadInt16();
py = reader.ReadInt16();
pi = reader.ReadUInt16();
if(!strifedata) texturedata.Seek(4, SeekOrigin.Current);
// Validate data
if((pi >= 0) && (pi < pnames.Length))
{
if(pnames[pi].Length > 0)
{
// Create patch on image
if(image != null) image.AddPatch(new TexturePatch(pnames[pi], px, py));
}
else
{
// Can't load image without name
General.ErrorLogger.Add(ErrorType.Error, "Can't use an unnamed patch referenced in \"" + sourcename + "\". Please consider giving names to your resources.");
}
}
}
// Add image to collection
images.Add(image);
}
else
{
// Skip patches data
texturedata.Seek(6 * patches, SeekOrigin.Current);
if(!strifedata) texturedata.Seek(4 * patches, SeekOrigin.Current);
}
}
}
19
Source : DeserializerStream.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public void rString(out string v)
{
ushort index = reader.ReadUInt16();
v = stringstable[index];
}
19
Source : DeserializerStream.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public void rUShort(out ushort v) { v = reader.ReadUInt16(); }
19
Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void ReadLinedefs(MapSet map, int firstindex,
Dictionary<int, Vertex> vertexlink, Dictionary<int, Sector> sectorlink)
{
MemoryStream linedefsmem, sidedefsmem;
BinaryReader readline, readside;
Lump linedefslump, sidedefslump;
int num, numsides, i, offsetx, offsety, v1, v2;
int s1, s2, flags, action, tag, sc;
Dictionary<string, bool> stringflags;
string thigh, tmid, tlow;
Linedef l;
Sidedef s;
// Get the linedefs lump from wad file
linedefslump = wad.FindLump("LINEDEFS", firstindex);
if(linedefslump == null) throw new Exception("Could not find required lump LINEDEFS!");
// Get the sidedefs lump from wad file
sidedefslump = wad.FindLump("SIDEDEFS", firstindex);
if(sidedefslump == null) throw new Exception("Could not find required lump SIDEDEFS!");
// Prepare to read the items
linedefsmem = new MemoryStream(linedefslump.Stream.ReadAllBytes());
sidedefsmem = new MemoryStream(sidedefslump.Stream.ReadAllBytes());
num = (int)linedefslump.Stream.Length / 14;
numsides = (int)sidedefslump.Stream.Length / 30;
readline = new BinaryReader(linedefsmem);
readside = new BinaryReader(sidedefsmem);
// Read items from the lump
// ano - heuristic to detect sidedef compression
if (num > numsides)
{
// ano - set sidedefs to some larger amount than
// numsides before resizing back down
// because in the case of sidedef compression the
// array will have to be resized a lot
map.SetCapacity(0, map.Linedefs.Count + num, map.Sidedefs.Count + (num * 2), 0, 0);
}
else
{
// ano - + 32 as extra leniency for some amount of sidedef
// compression that goes undetected by the prev check
// note this wont be resized back down but 32 is a neglible amount
map.SetCapacity(0, map.Linedefs.Count + num, map.Sidedefs.Count + num + 32, 0, 0);
}
for(i = 0; i < num; i++)
{
// Read properties from stream
v1 = readline.ReadUInt16();
v2 = readline.ReadUInt16();
flags = readline.ReadUInt16();
action = readline.ReadUInt16();
tag = readline.ReadUInt16();
s1 = readline.ReadUInt16();
s2 = readline.ReadUInt16();
// Make string flags
stringflags = new Dictionary<string, bool>();
foreach(string f in manager.Config.SortedLinedefFlags)
{
int fnum;
if(int.TryParse(f, out fnum)) stringflags[f] = ((flags & fnum) == fnum);
}
// Create new linedef
if(vertexlink.ContainsKey(v1) && vertexlink.ContainsKey(v2))
{
// Check if not zero-length
if(Vector2D.ManhattanDistance(vertexlink[v1].Position, vertexlink[v2].Position) > 0.0001f)
{
l = map.CreateLinedef(vertexlink[v1], vertexlink[v2]);
l.Update(stringflags, 0, tag, action, new int[Linedef.NUM_ARGS]);
l.UpdateCache();
// Line has a front side?
if(s1 != ushort.MaxValue)
{
// Read front sidedef
if((s1 * 30L) <= (sidedefsmem.Length - 30L))
{
sidedefsmem.Seek(s1 * 30, SeekOrigin.Begin);
offsetx = readside.ReadInt16();
offsety = readside.ReadInt16();
thigh = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
tlow = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
tmid = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
sc = readside.ReadUInt16();
// Create front sidedef
if(sectorlink.ContainsKey(sc))
{
s = map.CreateSidedef(l, true, sectorlink[sc]);
s.Update(offsetx, offsety, thigh, tmid, tlow);
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Sidedef " + s1 + " references invalid sector " + sc + ". Sidedef has been removed.");
}
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Linedef references invalid sidedef " + s1 + ". Sidedef has been removed.");
}
}
// Line has a back side?
if(s2 != ushort.MaxValue)
{
// Read back sidedef
if((s2 * 30L) <= (sidedefsmem.Length - 30L))
{
sidedefsmem.Seek(s2 * 30, SeekOrigin.Begin);
offsetx = readside.ReadInt16();
offsety = readside.ReadInt16();
thigh = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
tlow = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
tmid = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
sc = readside.ReadUInt16();
// Create back sidedef
if(sectorlink.ContainsKey(sc))
{
s = map.CreateSidedef(l, false, sectorlink[sc]);
s.Update(offsetx, offsety, thigh, tmid, tlow);
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Sidedef " + s2 + " references invalid sector " + sc + ". Sidedef has been removed.");
}
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " references invalid sidedef " + s2 + ". Sidedef has been removed.");
}
}
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " is zero-length. Linedef has been removed.");
}
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " references one or more invalid vertices. Linedef has been removed.");
}
}
if (num > numsides)
{
// ano - resize the arrays back down
map.SetCapacity(0, map.Linedefs.Count, map.Sidedefs.Count, 0, 0);
}
// Done
linedefsmem.Dispose();
sidedefsmem.Dispose();
}
19
Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void ReadThings(MapSet map, int firstindex)
{
MemoryStream mem;
BinaryReader reader;
int num, i, tag, z, action, x, y, type, flags, angle;
int[] args = new int[Thing.NUM_ARGS];
Dictionary<string, bool> stringflags;
Thing t;
// Get the lump from wad file
Lump lump = wad.FindLump("THINGS", firstindex);
if(lump == null) throw new Exception("Could not find required lump THINGS!");
// Prepare to read the items
mem = new MemoryStream(lump.Stream.ReadAllBytes());
num = (int)lump.Stream.Length / 20;
reader = new BinaryReader(mem);
// Read items from the lump
map.SetCapacity(0, 0, 0, 0, map.Things.Count + num);
for(i = 0; i < num; i++)
{
// Read properties from stream
tag = reader.ReadUInt16();
x = reader.ReadInt16();
y = reader.ReadInt16();
z = reader.ReadInt16();
angle = reader.ReadInt16();
type = reader.ReadUInt16();
flags = reader.ReadUInt16();
action = reader.ReadByte();
args[0] = reader.ReadByte();
args[1] = reader.ReadByte();
args[2] = reader.ReadByte();
args[3] = reader.ReadByte();
args[4] = reader.ReadByte();
// Make string flags
stringflags = new Dictionary<string, bool>();
foreach(KeyValuePair<string, string> f in manager.Config.ThingFlags)
{
int fnum;
if(int.TryParse(f.Key, out fnum)) stringflags[f.Key] = ((flags & fnum) == fnum);
}
// Create new item
t = map.CreateThing();
t.Update(type, x, y, z, angle, stringflags, tag, action, args);
}
// Done
mem.Dispose();
}
19
Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private Dictionary<int, Sector> ReadSectors(MapSet map, int firstindex)
{
MemoryStream mem;
Dictionary<int, Sector> link;
BinaryReader reader;
int num, i, hfloor, hceil, bright, special, tag;
string tfloor, tceil;
Sector s;
// Get the lump from wad file
Lump lump = wad.FindLump("SECTORS", firstindex);
if(lump == null) throw new Exception("Could not find required lump SECTORS!");
// Prepare to read the items
mem = new MemoryStream(lump.Stream.ReadAllBytes());
num = (int)lump.Stream.Length / 26;
reader = new BinaryReader(mem);
// Create lookup table
link = new Dictionary<int, Sector>(num);
// Read items from the lump
map.SetCapacity(0, 0, 0, map.Sectors.Count + num, 0);
for(i = 0; i < num; i++)
{
// Read properties from stream
hfloor = reader.ReadInt16();
hceil = reader.ReadInt16();
tfloor = Lump.MakeNormalName(reader.ReadBytes(8), WAD.ENCODING);
tceil = Lump.MakeNormalName(reader.ReadBytes(8), WAD.ENCODING);
bright = reader.ReadInt16();
special = reader.ReadUInt16();
tag = reader.ReadUInt16();
// Create new item
s = map.CreateSector();
s.Update(hfloor, hceil, tfloor, tceil, special, tag, bright);
// Add it to the lookup table
link.Add(i, s);
}
// Done
mem.Dispose();
// Return lookup table
return link;
}
19
Source : HexenMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void ReadLinedefs(MapSet map, int firstindex,
Dictionary<int, Vertex> vertexlink, Dictionary<int, Sector> sectorlink)
{
MemoryStream linedefsmem, sidedefsmem;
BinaryReader readline, readside;
Lump linedefslump, sidedefslump;
int num, numsides, i, offsetx, offsety, v1, v2;
int s1, s2, flags, action, sc;
int[] args = new int[Linedef.NUM_ARGS];
Dictionary<string, bool> stringflags;
string thigh, tmid, tlow;
Linedef l;
Sidedef s;
// Get the linedefs lump from wad file
linedefslump = wad.FindLump("LINEDEFS", firstindex);
if(linedefslump == null) throw new Exception("Could not find required lump LINEDEFS!");
// Get the sidedefs lump from wad file
sidedefslump = wad.FindLump("SIDEDEFS", firstindex);
if(sidedefslump == null) throw new Exception("Could not find required lump SIDEDEFS!");
// Prepare to read the items
linedefsmem = new MemoryStream(linedefslump.Stream.ReadAllBytes());
sidedefsmem = new MemoryStream(sidedefslump.Stream.ReadAllBytes());
num = (int)linedefslump.Stream.Length / 16;
numsides = (int)sidedefslump.Stream.Length / 30;
readline = new BinaryReader(linedefsmem);
readside = new BinaryReader(sidedefsmem);
// Read items from the lump
map.SetCapacity(0, map.Linedefs.Count + num, map.Sidedefs.Count + numsides, 0, 0);
for(i = 0; i < num; i++)
{
// Read properties from stream
v1 = readline.ReadUInt16();
v2 = readline.ReadUInt16();
flags = readline.ReadUInt16();
action = readline.ReadByte();
args[0] = readline.ReadByte();
args[1] = readline.ReadByte();
args[2] = readline.ReadByte();
args[3] = readline.ReadByte();
args[4] = readline.ReadByte();
s1 = readline.ReadUInt16();
s2 = readline.ReadUInt16();
// Make string flags
stringflags = new Dictionary<string, bool>();
foreach(string f in manager.Config.SortedLinedefFlags)
{
int fnum;
if(int.TryParse(f, out fnum)) stringflags[f] = ((flags & fnum) == fnum);
}
// Create new linedef
if(vertexlink.ContainsKey(v1) && vertexlink.ContainsKey(v2))
{
// Check if not zero-length
if(Vector2D.ManhattanDistance(vertexlink[v1].Position, vertexlink[v2].Position) > 0.0001f)
{
l = map.CreateLinedef(vertexlink[v1], vertexlink[v2]);
l.Update(stringflags, (flags & manager.Config.LinedefActivationsFilter), 0, action, args);
l.UpdateCache();
// Line has a front side?
if(s1 != ushort.MaxValue)
{
// Read front sidedef
sidedefsmem.Seek(s1 * 30, SeekOrigin.Begin);
if((s1 * 30L) <= (sidedefsmem.Length - 30L))
{
offsetx = readside.ReadInt16();
offsety = readside.ReadInt16();
thigh = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
tlow = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
tmid = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
sc = readside.ReadUInt16();
// Create front sidedef
if(sectorlink.ContainsKey(sc))
{
s = map.CreateSidedef(l, true, sectorlink[sc]);
s.Update(offsetx, offsety, thigh, tmid, tlow);
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Sidedef " + s1 + " references invalid sector " + sc + ". Sidedef has been removed.");
}
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " references invalid sidedef " + s1 + ". Sidedef has been removed.");
}
}
// Line has a back side?
if(s2 != ushort.MaxValue)
{
// Read back sidedef
sidedefsmem.Seek(s2 * 30, SeekOrigin.Begin);
if((s2 * 30L) <= (sidedefsmem.Length - 30L))
{
offsetx = readside.ReadInt16();
offsety = readside.ReadInt16();
thigh = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
tlow = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
tmid = Lump.MakeNormalName(readside.ReadBytes(8), WAD.ENCODING);
sc = readside.ReadUInt16();
// Create back sidedef
if(sectorlink.ContainsKey(sc))
{
s = map.CreateSidedef(l, false, sectorlink[sc]);
s.Update(offsetx, offsety, thigh, tmid, tlow);
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Sidedef " + s2 + " references invalid sector " + sc + ". Sidedef has been removed.");
}
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " references invalid sidedef " + s2 + ". Sidedef has been removed.");
}
}
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " is zero-length. Linedef has been removed.");
}
}
else
{
General.ErrorLogger.Add(ErrorType.Warning, "Linedef " + i + " references one or more invalid vertices. Linedef has been removed.");
}
}
// Done
linedefsmem.Dispose();
sidedefsmem.Dispose();
}
19
Source : DeserializerStream.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public void rwString(ref string v)
{
ushort index = reader.ReadUInt16();
v = stringstable[index];
}
19
Source : DeserializerStream.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public void rwUShort(ref ushort v) { v = reader.ReadUInt16(); }
19
Source : DoomMapSetIO.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
private void ReadThings(MapSet map, int firstindex)
{
MemoryStream mem;
BinaryReader reader;
int num, i, x, y, type, flags, angle;
Dictionary<string, bool> stringflags;
Thing t;
// Get the lump from wad file
Lump lump = wad.FindLump("THINGS", firstindex);
if(lump == null) throw new Exception("Could not find required lump THINGS!");
// Prepare to read the items
mem = new MemoryStream(lump.Stream.ReadAllBytes());
num = (int)lump.Stream.Length / 10;
reader = new BinaryReader(mem);
// Read items from the lump
map.SetCapacity(0, 0, 0, 0, map.Things.Count + num);
for(i = 0; i < num; i++)
{
// Read properties from stream
x = reader.ReadInt16();
y = reader.ReadInt16();
angle = reader.ReadInt16();
type = reader.ReadUInt16();
flags = reader.ReadUInt16();
// Make string flags
stringflags = new Dictionary<string, bool>();
foreach(KeyValuePair<string, string> f in manager.Config.ThingFlags)
{
int fnum;
if(int.TryParse(f.Key, out fnum)) stringflags[f.Key] = ((flags & fnum) == fnum);
}
// Create new item
t = map.CreateThing();
t.Update(type, x, y, 0, angle, stringflags, 0, 0, new int[Thing.NUM_ARGS]);
}
// Done
mem.Dispose();
}
19
Source : DynamicMethodBodyReader.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
void CreateExceptionHandlers() {
if (ehHeader != null) {
if (ehHeader.Length < 4)
return;
var reader = new BinaryReader(new MemoryStream(ehHeader));
byte b = reader.ReadByte();
if ((b & 0x40) == 0) { // DynamicResolver only checks bit 6
// Calculate num ehs exactly the same way that DynamicResolver does
int numHandlers = (ushort)((reader.ReadByte() - 2) / 12);
reader.ReadUInt16();
for (int i = 0; i < numHandlers; i++) {
if (reader.BaseStream.Position + 12 > reader.BaseStream.Length)
break;
var eh = new ExceptionHandler();
eh.HandlerType = (ExceptionHandlerType)reader.ReadUInt16();
int offs = reader.ReadUInt16();
eh.TryStart = GetInstructionThrow((uint)offs);
eh.TryEnd = GetInstruction((uint)(reader.ReadByte() + offs));
offs = reader.ReadUInt16();
eh.HandlerStart = GetInstructionThrow((uint)offs);
eh.HandlerEnd = GetInstruction((uint)(reader.ReadByte() + offs));
if (eh.HandlerType == ExceptionHandlerType.Catch)
eh.CatchType = ReadToken(reader.ReadUInt32()) as ITypeDefOrRef;
else if (eh.HandlerType == ExceptionHandlerType.Filter)
eh.FilterStart = GetInstruction(reader.ReadUInt32());
else
reader.ReadUInt32();
exceptionHandlers.Add(eh);
}
}
else {
reader.BaseStream.Position--;
int numHandlers = (ushort)(((reader.ReadUInt32() >> 8) - 4) / 24);
for (int i = 0; i < numHandlers; i++) {
if (reader.BaseStream.Position + 24 > reader.BaseStream.Length)
break;
var eh = new ExceptionHandler();
eh.HandlerType = (ExceptionHandlerType)reader.ReadUInt32();
var offs = reader.ReadUInt32();
eh.TryStart = GetInstructionThrow((uint)offs);
eh.TryEnd = GetInstruction((uint)(reader.ReadUInt32() + offs));
offs = reader.ReadUInt32();
eh.HandlerStart = GetInstructionThrow((uint)offs);
eh.HandlerEnd = GetInstruction((uint)(reader.ReadUInt32() + offs));
if (eh.HandlerType == ExceptionHandlerType.Catch)
eh.CatchType = ReadToken(reader.ReadUInt32()) as ITypeDefOrRef;
else if (eh.HandlerType == ExceptionHandlerType.Filter)
eh.FilterStart = GetInstruction(reader.ReadUInt32());
else
reader.ReadUInt32();
exceptionHandlers.Add(eh);
}
}
}
else if (ehInfos != null) {
foreach (var ehInfo in CreateExceptionInfos(ehInfos)) {
var tryStart = GetInstructionThrow((uint)ehInfo.StartAddr);
var tryEnd = GetInstruction((uint)ehInfo.EndAddr);
var endFinally = ehInfo.EndFinally < 0 ? null : GetInstruction((uint)ehInfo.EndFinally);
for (int i = 0; i < ehInfo.CurrentCatch; i++) {
var eh = new ExceptionHandler();
eh.HandlerType = (ExceptionHandlerType)ehInfo.Type[i];
eh.TryStart = tryStart;
eh.TryEnd = eh.HandlerType == ExceptionHandlerType.Finally ? endFinally : tryEnd;
eh.FilterStart = null; // not supported by DynamicMethod.ILGenerator
eh.HandlerStart = GetInstructionThrow((uint)ehInfo.CatchAddr[i]);
eh.HandlerEnd = GetInstruction((uint)ehInfo.CatchEndAddr[i]);
eh.CatchType = importer.Import(ehInfo.CatchClreplaced[i]);
exceptionHandlers.Add(eh);
}
}
}
}
19
Source : StrongNameKey.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
void Initialize(BinaryReader reader) {
try {
// Read PublicKeyBlob
signatureAlgorithm = (SignatureAlgorithm)reader.ReadUInt32();
hashAlgorithm = (replacedemblyHashAlgorithm)reader.ReadUInt32();
/*int pkLen = */reader.ReadInt32();
// Read PUBLICKEYSTRUC
if (reader.ReadByte() != 6)
throw new InvalidKeyException("Not a public key");
if (reader.ReadByte() != 2)
throw new InvalidKeyException("Invalid version");
reader.ReadUInt16(); // reserved
if ((SignatureAlgorithm)reader.ReadUInt32() != SignatureAlgorithm.CALG_RSA_SIGN)
throw new InvalidKeyException("Not RSA sign");
// Read RSAPUBKEY
if (reader.ReadUInt32() != RSA1_SIG) // magic = RSA1
throw new InvalidKeyException("Invalid RSA1 magic");
uint bitLength = reader.ReadUInt32();
publicExponent = reader.ReadBytesReverse(4);
modulus = reader.ReadBytesReverse((int)(bitLength / 8));
}
catch (IOException ex) {
throw new InvalidKeyException("Invalid public key", ex);
}
}
19
Source : StrongNameSigner.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
byte[] StrongNameHashData(replacedemblyHashAlgorithm hashAlg, long snSigOffset, uint snSigSize) {
var reader = new BinaryReader(stream);
snSigOffset += baseOffset;
long snSigOffsetEnd = snSigOffset + snSigSize;
using (var hasher = new replacedemblyHash(hashAlg)) {
byte[] buffer = new byte[0x8000];
// Hash the DOS header. It's defined to be all data from the start of
// the file up to the NT headers.
stream.Position = baseOffset + 0x3C;
uint ntHeadersOffs = reader.ReadUInt32();
stream.Position = baseOffset;
hasher.Hash(stream, ntHeadersOffs, buffer);
// Hash NT headers, but hash authenticode + checksum as 0s
stream.Position += 6;
int numSections = reader.ReadUInt16();
stream.Position -= 8;
hasher.Hash(stream, 0x18, buffer); // magic + FileHeader
bool is32bit = reader.ReadUInt16() == 0x010B;
stream.Position -= 2;
int optHeaderSize = is32bit ? 0x60 : 0x70;
if (stream.Read(buffer, 0, optHeaderSize) != optHeaderSize)
throw new IOException("Could not read data");
// Clear checksum
for (int i = 0; i < 4; i++)
buffer[0x40 + i] = 0;
hasher.Hash(buffer, 0, optHeaderSize);
const int imageDirsSize = 16 * 8;
if (stream.Read(buffer, 0, imageDirsSize) != imageDirsSize)
throw new IOException("Could not read data");
// Clear authenticode data dir
for (int i = 0; i < 8; i++)
buffer[4 * 8 + i] = 0;
hasher.Hash(buffer, 0, imageDirsSize);
// Hash section headers
long sectHeadersOffs = stream.Position;
hasher.Hash(stream, (uint)numSections * 0x28, buffer);
// Hash all raw section data but make sure we don't hash the location
// where the strong name signature will be stored.
for (int i = 0; i < numSections; i++) {
stream.Position = sectHeadersOffs + i * 0x28 + 0x10;
uint sizeOfRawData = reader.ReadUInt32();
uint pointerToRawData = reader.ReadUInt32();
stream.Position = baseOffset + pointerToRawData;
while (sizeOfRawData > 0) {
var pos = stream.Position;
if (snSigOffset <= pos && pos < snSigOffsetEnd) {
uint skipSize = (uint)(snSigOffsetEnd - pos);
if (skipSize >= sizeOfRawData)
break;
sizeOfRawData -= skipSize;
stream.Position += skipSize;
continue;
}
if (pos >= snSigOffsetEnd) {
hasher.Hash(stream, sizeOfRawData, buffer);
break;
}
uint maxLen = (uint)Math.Min(snSigOffset - pos, sizeOfRawData);
hasher.Hash(stream, maxLen, buffer);
sizeOfRawData -= maxLen;
}
}
return hasher.ComputeHash();
}
}
19
Source : PEExtensions.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
internal static uint CalculatePECheckSum(this BinaryReader reader, long length, long checkSumOffset) {
uint checkSum = 0;
for (long i = 0; i < length; i += 2) {
if (i == checkSumOffset) {
reader.ReadUInt32();
i += 2;
continue;
}
checkSum += reader.ReadUInt16();
checkSum = (ushort)(checkSum + (checkSum >> 16));
}
ulong cks = (ulong)checkSum + (ulong)length;
return (uint)cks + (uint)(cks >> 32);
}
19
Source : StrongNameKey.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public void Initialize(BinaryReader reader) {
/*
* Links:
* http://msdn.microsoft.com/en-us/library/cc250013%28v=prot.20%29.aspx
* http://msdn.microsoft.com/en-us/library/windows/desktop/aa387689%28v=vs.85%29.aspx
*
* struct PublicKeyBlob {
* unsigned int SigAlgID; // sig algorithm used to create the sig (00002400 = CALG_RSA_SIGN)
* unsigned int HashAlgID; // hash alg used to create the sig (usually 00008004 = CALG_SHA1)
* ULONG cbPublicKey; // Size of the data that follows
* // the rest is here
* }
*
* typedef struct _PUBLICKEYSTRUC {
* BYTE bType;
* BYTE bVersion;
* WORD reserved;
* ALG_ID aiKeyAlg;
* } BLOBHEADER, PUBLICKEYSTRUC;
*
* typedef struct _RSAPUBKEY {
* DWORD magic;
* DWORD bitlen;
* DWORD replacedxp;
* } RSAPUBKEY;
*
* Format of public key
* PublicKeyBlob
* PUBLICKEYSTRUC publickeystruc;
* RSAPUBKEY rsapubkey;
* BYTE modulus[rsapubkey.bitlen/8]
*
* Format of public/private key pair
* PUBLICKEYSTRUC publickeystruc;
* RSAPUBKEY rsapubkey;
* BYTE modulus[rsapubkey.bitlen/8];
* BYTE prime1[rsapubkey.bitlen/16]; // aka P
* BYTE prime2[rsapubkey.bitlen/16]; // aka Q
* BYTE exponent1[rsapubkey.bitlen/16]; // aka DP
* BYTE exponent2[rsapubkey.bitlen/16]; // aka DQ
* BYTE coefficient[rsapubkey.bitlen/16]; // aka IQ
* BYTE privateExponent[rsapubkey.bitlen/8];// aka D
*/
try {
publicKey = null;
// Read PUBLICKEYSTRUC
if (reader.ReadByte() != 7)
throw new InvalidKeyException("Not a public/private key pair");
if (reader.ReadByte() != 2)
throw new InvalidKeyException("Invalid version");
reader.ReadUInt16(); // reserved
if ((SignatureAlgorithm)reader.ReadUInt32() != SignatureAlgorithm.CALG_RSA_SIGN)
throw new InvalidKeyException("Not RSA sign");
// Read RSAPUBKEY
if (reader.ReadUInt32() != RSA2_SIG) // magic = RSA2
throw new InvalidKeyException("Invalid RSA2 magic");
uint bitLength = reader.ReadUInt32();
publicExponent = reader.ReadBytesReverse(4);
int len8 = (int)(bitLength / 8);
int len16 = (int)(bitLength / 16);
// Read the rest
modulus = reader.ReadBytesReverse(len8);
prime1 = reader.ReadBytesReverse(len16);
prime2 = reader.ReadBytesReverse(len16);
exponent1 = reader.ReadBytesReverse(len16);
exponent2 = reader.ReadBytesReverse(len16);
coefficient = reader.ReadBytesReverse(len16);
privateExponent = reader.ReadBytesReverse(len8);
}
catch (IOException ex) {
throw new InvalidKeyException("Couldn't read strong name key", ex);
}
}
19
Source : EndianBinaryReader.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public override ushort ReadUInt16()
{
return EndianSupport.SwitchEndian(base.ReadUInt16());
}
19
Source : ExtendedBinaryReader.cs
with GNU Lesser General Public License v3.0
from Apollo3zehn
with GNU Lesser General Public License v3.0
from Apollo3zehn
public ushort ReadUInt16Reverse()
{
return this.ReadReverse<ushort>(BitConverter.GetBytes(this.ReadUInt16()));
}
19
Source : ExcelVBAProject.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private void ReadDirStream()
{
byte[] dir = VBACompression.DecompressPart(Doreplacedent.Storage.SubStorage["VBA"].DataStreams["dir"]);
MemoryStream ms = new MemoryStream(dir);
BinaryReader br = new BinaryReader(ms);
ExcelVbaReference currentRef = null;
string referenceName = "";
ExcelVBAModule currentModule = null;
bool terminate = false;
while (br.BaseStream.Position < br.BaseStream.Length && terminate == false)
{
ushort id = br.ReadUInt16();
uint size = br.ReadUInt32();
switch (id)
{
case 0x01:
SystemKind = (eSyskind)br.ReadUInt32();
break;
case 0x02:
Lcid = (int)br.ReadUInt32();
break;
case 0x03:
CodePage = (int)br.ReadUInt16();
break;
case 0x04:
Name = GetString(br, size);
break;
case 0x05:
Description = GetUnicodeString(br, size);
break;
case 0x06:
HelpFile1 = GetString(br, size);
break;
case 0x3D:
HelpFile2 = GetString(br, size);
break;
case 0x07:
HelpContextID = (int)br.ReadUInt32();
break;
case 0x08:
LibFlags = (int)br.ReadUInt32();
break;
case 0x09:
MajorVersion = (int)br.ReadUInt32();
MinorVersion = (int)br.ReadUInt16();
break;
case 0x0C:
Constants = GetUnicodeString(br, size);
break;
case 0x0D:
uint sizeLibID = br.ReadUInt32();
var regRef = new ExcelVbaReference();
regRef.Name = referenceName;
regRef.ReferenceRecordID = id;
regRef.Libid = GetString(br, sizeLibID);
uint reserved1 = br.ReadUInt32();
ushort reserved2 = br.ReadUInt16();
References.Add(regRef);
break;
case 0x0E:
var projRef = new ExcelVbaReferenceProject();
projRef.ReferenceRecordID = id;
projRef.Name = referenceName;
sizeLibID = br.ReadUInt32();
projRef.Libid = GetString(br, sizeLibID);
sizeLibID = br.ReadUInt32();
projRef.LibIdRelative = GetString(br, sizeLibID);
projRef.MajorVersion = br.ReadUInt32();
projRef.MinorVersion = br.ReadUInt16();
References.Add(projRef);
break;
case 0x0F:
ushort modualCount = br.ReadUInt16();
break;
case 0x13:
ushort cookie = br.ReadUInt16();
break;
case 0x14:
LcidInvoke = (int)br.ReadUInt32();
break;
case 0x16:
referenceName = GetUnicodeString(br, size);
break;
case 0x19:
currentModule = new ExcelVBAModule();
currentModule.Name = GetUnicodeString(br, size);
Modules.Add(currentModule);
break;
case 0x1A:
currentModule.streamName = GetUnicodeString(br, size);
break;
case 0x1C:
currentModule.Description = GetUnicodeString(br, size);
break;
case 0x1E:
currentModule.HelpContext = (int)br.ReadUInt32();
break;
case 0x21:
case 0x22:
break;
case 0x2B: //Modul Terminator
break;
case 0x2C:
currentModule.Cookie = br.ReadUInt16();
break;
case 0x31:
currentModule.ModuleOffset = br.ReadUInt32();
break;
case 0x10:
terminate = true;
break;
case 0x30:
var extRef = (ExcelVbaReferenceControl)currentRef;
var sizeExt = br.ReadUInt32();
extRef.LibIdExternal = GetString(br, sizeExt);
uint reserved4 = br.ReadUInt32();
ushort reserved5 = br.ReadUInt16();
extRef.OriginalTypeLib = new Guid(br.ReadBytes(16));
extRef.Cookie = br.ReadUInt32();
break;
case 0x33:
currentRef = new ExcelVbaReferenceControl();
currentRef.ReferenceRecordID = id;
currentRef.Name = referenceName;
currentRef.Libid = GetString(br, size);
References.Add(currentRef);
break;
case 0x2F:
var contrRef = (ExcelVbaReferenceControl)currentRef;
contrRef.ReferenceRecordID = id;
var sizeTwiddled = br.ReadUInt32();
contrRef.LibIdTwiddled = GetString(br, sizeTwiddled);
var r1 = br.ReadUInt32();
var r2 = br.ReadUInt16();
break;
case 0x25:
currentModule.ReadOnly = true;
break;
case 0x28:
currentModule.Private = true;
break;
default:
break;
}
}
}
19
Source : ExcelVBAProject.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private string GetUnicodeString(BinaryReader br, uint size)
{
string s = GetString(br, size);
int reserved = br.ReadUInt16();
uint sizeUC = br.ReadUInt32();
string sUC = GetString(br, sizeUC, System.Text.Encoding.Unicode);
return sUC.Length == 0 ? s : sUC;
}
19
Source : ExcelVBASignature.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
private void GetSignature()
{
if (_vbaPart == null) return;
var rel = _vbaPart.GetRelationshipsByType(schemaRelVbaSignature).FirstOrDefault();
if (rel != null)
{
Uri = UriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri);
Part = _vbaPart.Package.GetPart(Uri);
var stream = Part.GetStream();
BinaryReader br = new BinaryReader(stream);
uint cbSignature = br.ReadUInt32();
uint signatureOffset = br.ReadUInt32(); //44 ??
uint cbSigningCertStore = br.ReadUInt32();
uint certStoreOffset = br.ReadUInt32();
uint cbProjectName = br.ReadUInt32();
uint projectNameOffset = br.ReadUInt32();
uint fTimestamp = br.ReadUInt32();
uint cbTimestampUrl = br.ReadUInt32();
uint timestampUrlOffset = br.ReadUInt32();
byte[] signature = br.ReadBytes((int)cbSignature);
uint version = br.ReadUInt32();
uint fileType = br.ReadUInt32();
uint id = br.ReadUInt32();
while (id != 0)
{
uint encodingType = br.ReadUInt32();
uint length = br.ReadUInt32();
if (length > 0)
{
byte[] value = br.ReadBytes((int)length);
switch (id)
{
//Add property values here...
case 0x20:
Certificate = new X509Certificate2(value);
break;
default:
break;
}
}
id = br.ReadUInt32();
}
uint endel1 = br.ReadUInt32(); //0
uint endel2 = br.ReadUInt32(); //0
ushort rgchProjectNameBuffer = br.ReadUInt16();
ushort rgchTimestampBuffer = br.ReadUInt16();
#if Core
Verifier = new EnvelopedCms();
#else
Verifier = new SignedCms();
#endif
Verifier.Decode(signature);
}
else
{
Certificate = null;
Verifier = null;
}
}
19
Source : RSAHelper.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public RSA CreateRsaProviderFromPublicKey( string publicKeyString ) {
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] seq = new byte[15];
var x509Key = System.Convert.FromBase64String( publicKeyString );
// --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
using( MemoryStream mem = new MemoryStream( x509Key ) ) {
using( BinaryReader binr = new BinaryReader( mem ) ) //wrap Memory Stream with BinaryReader for easy reading
{
byte bt = 0;
ushort twobytes = 0;
twobytes = binr.ReadUInt16();
if( twobytes == 0x8130 ) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if( twobytes == 0x8230 )
binr.ReadInt16(); //advance 2 bytes
else
return null;
seq = binr.ReadBytes( 15 ); //read the Sequence OID
if( !CompareBytearrays( seq, seqOid ) ) //make sure Sequence for OID is correct
return null;
twobytes = binr.ReadUInt16();
if( twobytes == 0x8103 ) //data read as little endian order (actual data order for Bit String is 03 81)
binr.ReadByte(); //advance 1 byte
else if( twobytes == 0x8203 )
binr.ReadInt16(); //advance 2 bytes
else
return null;
bt = binr.ReadByte();
if( bt != 0x00 ) //expect null byte next
return null;
twobytes = binr.ReadUInt16();
if( twobytes == 0x8130 ) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if( twobytes == 0x8230 )
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
byte lowbyte = 0x00;
byte highbyte = 0x00;
if( twobytes == 0x8102 ) //data read as little endian order (actual data order for Integer is 02 81)
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
else if( twobytes == 0x8202 ) {
highbyte = binr.ReadByte(); //advance 2 bytes
lowbyte = binr.ReadByte();
}
else
return null;
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
int modsize = BitConverter.ToInt32( modint, 0 );
int firstbyte = binr.PeekChar();
if( firstbyte == 0x00 ) { //if first byte (highest order) of modulus is zero, don't include it
binr.ReadByte(); //skip this null byte
modsize -= 1; //reduce modulus buffer size by 1
}
byte[] modulus = binr.ReadBytes( modsize ); //read the modulus bytes
if( binr.ReadByte() != 0x02 ) //expect an Integer for the exponent data
return null;
int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
byte[] exponent = binr.ReadBytes( expbytes );
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
var rsa = RSA.Create();
RSAParameters rsaKeyInfo = new RSAParameters {
Modulus = modulus,
Exponent = exponent
};
rsa.ImportParameters( rsaKeyInfo );
return rsa;
}
}
}
19
Source : RSAHelper.cs
with MIT License
from aprilyush
with MIT License
from aprilyush
public RSA CreateRsaProviderFromPrivateKey( string privateKey ) {
var privateKeyBits = System.Convert.FromBase64String( privateKey );
var rsa = RSA.Create();
var rsaParameters = new RSAParameters();
using( BinaryReader binr = new BinaryReader( new MemoryStream( privateKeyBits ) ) ) {
byte bt = 0;
ushort twobytes = 0;
twobytes = binr.ReadUInt16();
if( twobytes == 0x8130 )
binr.ReadByte();
else if( twobytes == 0x8230 )
binr.ReadInt16();
else
throw new Exception( "Unexpected value read binr.ReadUInt16()" );
twobytes = binr.ReadUInt16();
if( twobytes != 0x0102 )
throw new Exception( "Unexpected version" );
bt = binr.ReadByte();
if( bt != 0x00 )
throw new Exception( "Unexpected value read binr.ReadByte()" );
rsaParameters.Modulus = binr.ReadBytes( GetIntegerSize( binr ) );
rsaParameters.Exponent = binr.ReadBytes( GetIntegerSize( binr ) );
rsaParameters.D = binr.ReadBytes( GetIntegerSize( binr ) );
rsaParameters.P = binr.ReadBytes( GetIntegerSize( binr ) );
rsaParameters.Q = binr.ReadBytes( GetIntegerSize( binr ) );
rsaParameters.DP = binr.ReadBytes( GetIntegerSize( binr ) );
rsaParameters.DQ = binr.ReadBytes( GetIntegerSize( binr ) );
rsaParameters.InverseQ = binr.ReadBytes( GetIntegerSize( binr ) );
}
rsa.ImportParameters( rsaParameters );
return rsa;
}
19
Source : BinaryReader.cs
with MIT License
from araditc
with MIT License
from araditc
public static ushort ReadUInt16(this BinaryReader reader, bool bigEndian) {
if (!bigEndian)
return reader.ReadUInt16();
int ret = 0;
ret |= (reader.ReadByte() << 8);
ret |= (reader.ReadByte() << 0);
return (ushort) ret;
}
19
Source : SocksReply.cs
with MIT License
from araditc
with MIT License
from araditc
public static SocksReply Deserialize(byte[] buffer) {
buffer.ThrowIfNull("buffer");
using (var ms = new MemoryStream(buffer)) {
using (BinaryReader r = new BinaryReader(ms)) {
if (r.ReadByte() != version)
throw new SerializationException("Invalid SOCKS5 reply.");
ReplyStatus status = (ReplyStatus) r.ReadByte();
// Skip reserved octet.
r.ReadByte();
ATyp atyp = (ATyp) r.ReadByte();
IPAddress addr = null;
string domain = null;
switch (atyp) {
case ATyp.IPv4:
case ATyp.IPv6:
addr = new IPAddress(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16));
break;
case ATyp.Domain:
byte len = r.ReadByte();
domain = Encoding.ASCII.GetString(r.ReadBytes(len));
break;
}
ushort port = r.ReadUInt16(true);
if (atyp == ATyp.Domain)
return new SocksReply(status, domain, port);
return new SocksReply(status, addr, port);
}
}
}
19
Source : SocksRequest.cs
with MIT License
from araditc
with MIT License
from araditc
public static SocksRequest Deserialize(byte[] buffer) {
using (var ms = new MemoryStream(buffer)) {
using (BinaryReader r = new BinaryReader(ms)) {
if (r.ReadByte() != version)
throw new SerializationException("Invalid SOCKS5 request.");
SocksCommand command = (SocksCommand) r.ReadByte();
// Skip reserved octet.
r.ReadByte();
ATyp atyp = (ATyp) r.ReadByte();
IPAddress addr = null;
string domain = null;
switch (atyp) {
case ATyp.IPv4:
case ATyp.IPv6:
addr = new IPAddress(r.ReadBytes(atyp == ATyp.IPv4 ? 4 : 16));
break;
case ATyp.Domain:
byte len = r.ReadByte();
domain = Encoding.ASCII.GetString(r.ReadBytes(len));
break;
}
ushort port = r.ReadUInt16(true);
if (atyp == ATyp.Domain)
return new SocksRequest(command, domain, port);
return new SocksRequest(command, addr, port);
}
}
}
19
Source : RealLiveDisassembler.cs
with MIT License
from arcusmaximus
with MIT License
from arcusmaximus
private bool Read()
{
char opcode = (char)_reader.ReadByte();
switch (opcode)
{
case '\0':
return false;
case '\n':
_reader.ReadUInt16();
return true;
case '!':
case '@':
ReadKidokuFlag();
return true;
case ',':
case '?':
return true;
case '#':
ReadFunctionCall();
return true;
case '$':
ReadExpression();
return true;
case '\\':
case 'a':
_reader.ReadByte();
return true;
case '(':
_stream.Position--;
ReadItemList('(', ')');
return true;
case '{':
_stream.Position--;
ReadItemList('{', '}');
return true;
case '"':
_stream.Position--;
ReadQuotedString();
return true;
default:
_stream.Position--;
ReadUnquotedString();
return true;
}
}
19
Source : RealLiveDisassembler.cs
with MIT License
from arcusmaximus
with MIT License
from arcusmaximus
private void ReadKidokuFlag()
{
int lineNumberIndex = _reader.ReadUInt16();
int pos = (int)_stream.Position;
_stream.Position = _lineNumbersOffset + 4 * lineNumberIndex;
int lineNumber = _reader.ReadInt32() - 1000000;
if (lineNumber >= 0)
{
int entryPointOffset = 0x34 + lineNumber * 4;
AddressEncountered?.Invoke(entryPointOffset);
}
_stream.Position = pos;
}
19
Source : RealLiveDisassembler.cs
with MIT License
from arcusmaximus
with MIT License
from arcusmaximus
private void ReadFunctionCall()
{
byte type = _reader.ReadByte();
_currentModule = _reader.ReadByte();
_currentFunction = _reader.ReadUInt16();
ushort numArgs = _reader.ReadUInt16();
byte overload = _reader.ReadByte();
if (!IsCurrentFunctionOneOf(ParameterlessGoToFunctions) && (char)_reader.PeekByte() == '(')
ReadItemList('(', ')');
if (IsCurrentFunctionOneOf(GoToFunctions))
ReadGoTo();
else if (IsCurrentFunctionOneOf(GoToOnFunctions))
ReadGoToOn(numArgs);
else if (IsCurrentFunctionOneOf(GoToCaseFunctions))
ReadGoToCase();
else if (_currentModule == SelectModule)
ReadSelect();
_currentModule = null;
_currentFunction = null;
}
19
Source : Disassembler.cs
with MIT License
from arcusmaximus
with MIT License
from arcusmaximus
private bool ProcessGetLocalVariableAddress()
{
int offset = _reader.ReadUInt16();
_currentInstr.Append($"lea var{offset:X}");
return true;
}
19
Source : Disassembler.cs
with MIT License
from arcusmaximus
with MIT License
from arcusmaximus
private void ProcessShortOperand()
{
ushort value = _reader.ReadUInt16();
_currentInstr.Append(value.ToString("X"));
}
19
Source : CatSystemScript.cs
with MIT License
from arcusmaximus
with MIT License
from arcusmaximus
private static byte[] Decompress(byte[] inputData)
{
MemoryStream inputStream = new MemoryStream(inputData);
BinaryReader reader = new BinaryReader(inputStream);
byte[] magic = reader.ReadBytes(8);
if (!magic.SequenceEqual(Magic))
throw new InvalidDataException("Invalid magic");
int compressedLength = reader.ReadInt32();
int uncompressedLength = reader.ReadInt32();
if (compressedLength == 0)
{
if (uncompressedLength != inputStream.Length - 0x10)
throw new InvalidDataException("Invalid size");
return reader.ReadBytes(uncompressedLength);
}
else
{
if (compressedLength != inputStream.Length - 0x10)
throw new InvalidDataException("Invalid compressed size");
ushort zlibHeader = reader.ReadUInt16();
byte[] uncompressedData = new byte[uncompressedLength];
using (DeflateStream decompressionStream = new DeflateStream(inputStream, CompressionMode.Decompress))
{
decompressionStream.Read(uncompressedData, 0, uncompressedData.Length);
}
return uncompressedData;
}
}
19
Source : Card_Manager.cs
with MIT License
from Arefu
with MIT License
from Arefu
private void LoadCardNameTypes(Dictionary<short, Card_Info> cards,
IDictionary<CardNameType, HashSet<short>> cardNameTypes)
{
using (var reader =
new BinaryReader(new MemoryStream(Manager.Archive.Root.FindFile("bin/CARD_Named.bin").LoadBuffer())))
{
var numArchetypes = reader.ReadUInt16();
var numCards = reader.ReadUInt16();
long cardsStartOffset = 4 + numArchetypes * 4;
var cardsEndOffset = cardsStartOffset + numCards * 2;
Debug.replacedert(reader.BaseStream.Length == cardsEndOffset);
for (var i = 0; i < numArchetypes; i++)
{
int offset = reader.ReadInt16();
int count = reader.ReadInt16();
var cardIds = new HashSet<short>();
cardNameTypes.Add((CardNameType) i, cardIds);
var tempOffset = reader.BaseStream.Position;
reader.BaseStream.Position = cardsStartOffset + offset * 2;
for (var j = 0; j < count; j++)
{
var cardId = reader.ReadInt16();
Cards[cardId].NameTypes.Add((CardNameType) i);
cardIds.Add(cardId);
}
reader.BaseStream.Position = tempOffset;
}
}
}
19
Source : How_To_Play.cs
with MIT License
from Arefu
with MIT License
from Arefu
public override void Load(BinaryReader reader, long length)
{
Entries.Clear();
var dataOffset = reader.BaseStream.Position;
var count = Endian.ConvertUInt32(reader.ReadUInt32());
var startChunkLen = count * 8 + 4;
if (startChunkLen % align != 0) startChunkLen += align - startChunkLen % align;
var stringOffset = dataOffset + startChunkLen;
for (var i = 0; i < count; i++)
{
var placeholderBytes = reader.ReadUInt32();
Debug.replacedert(placeholderBytes == 0, "Unexpected placeholder data in howtoplay bin file");
var type = (EntryType) reader.ReadByte();
var imageId = reader.ReadByte();
var len = Endian.ConvertUInt16(reader.ReadUInt16());
var tempOffset = reader.BaseStream.Position;
reader.BaseStream.Position = stringOffset;
var str = Encoding.BigEndianUnicode.GetString(reader.ReadBytes(len * 2));
reader.BaseStream.Position = tempOffset;
var entry = new Entry(str, type, imageId);
Entries.Add(entry);
stringOffset += len * 2 + 2;
}
}
19
Source : Related_Card_Data.cs
with MIT License
from Arefu
with MIT License
from Arefu
public override void Load(BinaryReader reader, long length)
{
Clear();
var dataStart = reader.BaseStream.Position + Constants.NumCards * 8;
for (var i = 0; i < Constants.NumCards; i++)
{
var shortoffset = reader.ReadUInt32();
var tagCount = reader.ReadUInt32();
var tempOffset = reader.BaseStream.Position;
var start = dataStart + shortoffset * 4;
reader.BaseStream.Position = start;
var items = new List<Item>();
for (var j = 0; j < tagCount; j++) items.Add(new Item(reader.ReadUInt16(), reader.ReadUInt16()));
Items.Add(items);
reader.BaseStream.Position = tempOffset;
}
}
See More Examples