public static CertPrivateKey ImportPrivateKey(EncodingFormat fmt, Stream source) { if (fmt != EncodingFormat.PEM) { throw new NotSupportedException("Unsupported archive format"); } using (var tr = new StreamReader(source)) { var pr = new PemReader(tr); var pem = pr.ReadObject(); var ackp = pem as AsymmetricCipherKeyPair; if (ackp != null) { var rsa = ackp.Private as RsaPrivateCrtKeyParameters; if (rsa != null) { return(new CertPrivateKey { KeyPair = ackp, }); } } throw new InvalidDataException("could not read source as PEM private key"); } }
private static string getStringfromEncodingFormat(EncodingFormat format) { switch (format) { case EncodingFormat.PNG: return(".png"); case EncodingFormat.JPEG: return(".jpg"); case EncodingFormat.TIFF: return(".tif"); case EncodingFormat.WebP: return(".webp"); case EncodingFormat.Bitmap: return(".bmp"); case EncodingFormat.JPEG2000: return(".jp2"); case EncodingFormat.PBM: return(".pbm"); case EncodingFormat.Raster: return(".ras"); default: throw new ArgumentOutOfRangeException($@"""{nameof(format)}"" is not a valid export format."); } }
// For reading mips_encode.dat public void ReadEncodeList() { StreamReader reader = new StreamReader("mips_encode.dat"); try { while (reader.Peek() != -1) { string line = reader.ReadLine(); line = RemoveSpaces(line); string[] lineArray = line.Split(':'); EncodingFormat encoding = new EncodingFormat(); encoding.command = lineArray[0]; encoding.type = Convert.ToInt32(lineArray[1]); encoding.format = lineArray[2]; encodeList.Add(encoding); } } catch { } finally { reader.Close(); } }
public override void ExportCertificate(Crt cert, EncodingFormat fmt, Stream target) { string outform; switch (fmt) { case EncodingFormat.PEM: outform = "PEM"; break; case EncodingFormat.DER: outform = "DER"; break; default: throw new NotSupportedException("unsupported encoding format"); } var tempSource = Path.GetTempFileName(); var tempTarget = Path.GetTempFileName(); try { File.WriteAllText(tempSource, cert.Pem); RunCli($"x509 -inform PEM -in {tempSource} -outform {outform} -out {tempTarget}"); var targetBytes = File.ReadAllBytes(tempTarget); target.Write(targetBytes, 0, targetBytes.Length); } finally { File.Delete(tempSource); File.Delete(tempTarget); } }
public override Csr ImportCsr(EncodingFormat fmt, Stream source) { if (fmt == EncodingFormat.PEM) { using (var tr = new StreamReader(source)) { PemReader pr = new PemReader(tr); var csr = (Pkcs10CertificationRequest)pr.ReadObject(); return(new Csr(ToCsrPem(csr))); } } else if (fmt == EncodingFormat.DER) { using (var ms = new MemoryStream()) { source.CopyTo(ms); var csr = new Pkcs10CertificationRequest(ms.ToArray()); return(new Csr(ToCsrPem(csr))); } } else { throw new NotSupportedException("unsupported encoding format"); } }
public string Encode() => this.Encode(WorkflowSymbol.DefaultEncodingFormat); // default format /// <summary> /// Encodes the specified encoding format. /// </summary> /// <param name="encodingFormat">The encoding format.</param> /// <returns>System.String.</returns> /// <exception cref="SerializationException"></exception> internal string Encode(EncodingFormat encodingFormat) { using var ms = new MemoryStream(); using var writer = new BinaryWriter(ms); if (this.checksum != null) { writer.Write((byte)(encodingFormat | EncodingFormat.Checksum)); SymbolHelper.WriteEncodedInt32(writer, this.checksum.Length); writer.Write(this.checksum); } else { writer.Write((byte)encodingFormat); } switch (encodingFormat) { case EncodingFormat.Binary: this.Write(writer); break; case EncodingFormat.String: writer.Write(this.ToString()); break; default: throw FxTrace.Exception.AsError(new SerializationException()); } // Need to copy to a buffer to trim excess capacity. var buffer = new byte[ms.Length]; Array.Copy(ms.GetBuffer(), buffer, ms.Length); return(Convert.ToBase64String(buffer)); }
// Decode from Base64 string. public static WorkflowSymbol Decode(string symbolString) { byte[] data = Convert.FromBase64String(symbolString); using (BinaryReader reader = new BinaryReader(new MemoryStream(data))) { byte[] checksum = null; EncodingFormat format = (EncodingFormat)reader.ReadByte(); int payloadBytesCount = data.Length - sizeof(EncodingFormat); if (0 != (format & EncodingFormat.Checksum)) { int bytesCount = SymbolHelper.ReadEncodedInt32(reader); checksum = reader.ReadBytes(bytesCount); payloadBytesCount -= SymbolHelper.GetEncodedSize(bytesCount); format &= (~EncodingFormat.Checksum); } switch (format) { case EncodingFormat.Binary: return(ParseBinary(reader.ReadBytes(payloadBytesCount), checksum)); // Compute the case EncodingFormat.String: return(ParseStringRepresentation(reader.ReadString(), checksum)); } } throw FxTrace.Exception.AsError(new SerializationException()); }
public override PrivateKey ImportPrivateKey <PK>(EncodingFormat fmt, Stream source) { if (typeof(PK) == typeof(RsaPrivateKey)) { using (var tr = new StreamReader(source)) { var pr = new PemReader(tr); var pem = pr.ReadObject(); var ackp = pem as AsymmetricCipherKeyPair; if (ackp != null) { var rsa = ackp.Private as RsaPrivateCrtKeyParameters; if (rsa != null) { return(new RsaPrivateKey( rsa.Modulus.BitLength, rsa.Exponent.ToString(16), ToPrivatePem(ackp))); } } } throw new NotSupportedException("unsupported or invalid private key PEM content"); } else { throw new NotSupportedException("unsupported private key type"); } }
public XnaRecorder(Stream stream, EncodingFormat format, int preset) { if (stream == null) { throw new ArgumentNullException("stream"); } _stream = stream; _sampleRate = 16000; _bitRate = 16; _channels = 1; _format = format; _preset = preset; _size = 0; _duration = 0; _state = RecorderState.Unknown; InitializeMicrophone(); if (_format == EncodingFormat.Wave) { _writer = new WaveWriter(_stream, _sampleRate, _bitRate, _channels); } else if (_format == EncodingFormat.MP3) { _writer = new Mp3Writer(_stream, _sampleRate, _bitRate, _channels, (LAMEPreset)_preset); } }
public void AsyncClientShouldNotThrowExceptionWithInvalidCredential() { client.UserId = "invalid_id"; client.UserKey = "invalid_key"; Assert.DoesNotThrow(() => { client.GetMediaListAsync( (mediaList) => { }, (errors) => { }); }); Uri[] sources = new Uri[]{}; EncodingFormat[] formats = new EncodingFormat[]{}; Assert.DoesNotThrow(() => { client.AddMediaAsync(sources, formats, (mediaId) => { }, (errors) => { }); }); }
public override PrivateKey ImportPrivateKey <PK>(EncodingFormat fmt, Stream source) { if (typeof(PK) == typeof(RsaPrivateKey)) { using (BIO keyBio = BIO.MemoryBuffer()) { using (var ms = new MemoryStream()) { source.CopyTo(ms); keyBio.Write(ms.ToArray()); } using (var key = CryptoKey.FromPrivateKey(keyBio, null)) { var rsa = key.GetRSA(); return(new RsaPrivateKey(rsa.Size, rsa.PrivateExponent.ToHexString(), rsa.PrivateKeyAsPEM)); } } } else { throw new NotSupportedException("unsupported private key type"); } }
public void TestImportRsaPrivatekey(EncodingFormat fmt, string filePath) { using (var cp = GetCP()) { using (var source = new FileStream(filePath, FileMode.Open)) { var pk = cp.ImportPrivateKey<RsaPrivateKey>(fmt, source); } } }
private void TestImportCertificate(EncodingFormat fmt, string filePath) { using (var cp = CertificateProvider.GetProvider()) { using (var source = new FileStream(filePath, FileMode.Open)) { var crt = cp.ImportCertificate(fmt, source); } } }
public void TestImportRsaPrivatekey(EncodingFormat fmt, string filePath) { using (var cp = GetCP()) { using (var source = new FileStream(filePath, FileMode.Open)) { var pk = cp.ImportPrivateKey <RsaPrivateKey>(fmt, source); } } }
/// <summary> /// Create a new virtual camera device from a file. /// </summary> /// <param name="filePath">File relative to the executing application.</param> /// <param name="format">Image format used for encoding.</param> /// <param name="encodingParams">An array of parameters used for encoding.</param> public CameraVirtual(string filePath, EncodingFormat format = EncodingFormat.PNG, Dictionary <ImwriteFlags, int> encodingParams = null) : base(format, encodingParams) { if (!File.Exists(filePath)) { throw new FileNotFoundException($"\"{filePath}\" is not found."); } FilePath = filePath; Capture = new VideoCapture(FilePath, api); }
static String toHexAddr(Byte[] rawData, EncodingFormat format, Int32 start, Int32 count, Boolean forceUpperCase) { count = getCount(rawData.Length, start, count); StringBuilder SB = new StringBuilder(); Int32 rowCount = 0, n = 0; Int32 addrLength = getAddrLength(rawData.Length); for (Int32 index = start; index < start + count; index++) { if (n % 16 == 0) { String addr = Convert.ToString(rowCount, 16).PadLeft(addrLength, '0'); if (forceUpperCase) { addr = addr.ToUpper(); } SB.Append(addr); SB.Append(" "); rowCount += 16; } byteToHexOctet(SB, rawData[index], forceUpperCase); if (index == start) { SB.Append(" "); n++; continue; } if ((n + 1) % 16 == 0) { SB.Append(format == EncodingFormat.NOCR ? "\n" : "\r\n"); } else if ((n + 1) % 8 == 0) { SB.Append(" "); } else { SB.Append(" "); } n++; } switch (format) { case EncodingFormat.NOCR: SB.Append('\n'); break; case EncodingFormat.NOCRLF: break; default: SB.Append("\r\n"); break; } return(SB.ToString()); }
private static WaveFormatEncoding GetWaveEncodingFormat(EncodingFormat encoding) { switch (encoding) { case EncodingFormat.Pcm: return(WaveFormatEncoding.LPCM); default: return(WaveFormatEncoding.Unknown); } }
static String toHex(Byte[] rawData, EncodingFormat format, Int32 start, Int32 count, Boolean forceUpperCase) { count = getCount(rawData.Length, start, count); StringBuilder SB = new StringBuilder(); //if (format == EncodingFormat.NOCRLF) { // for (Int32 i = start; i < start + count; i++) { //byteToHexOctet(SB, rawData[i], forceUpperCase); //} // return SB.Remove(SB.Length - 1, 1).ToString(); //} Int32 n = 0; for (Int32 index = start; index < start + count; index++) { n++; byteToHexOctet(SB, rawData[index], forceUpperCase); if (index == start) { SB.Append(" "); continue; } if (n % 16 == 0) { switch (format) { case EncodingFormat.NOCRLF: SB.Append(" "); break; case EncodingFormat.CRLF: SB.Append("\r\n"); break; case EncodingFormat.NOCR: SB.Append("\n"); break; } } else if (n % 8 == 0 && format != EncodingFormat.NOCRLF) { SB.Append(" "); } else { SB.Append(" "); } } switch (format) { case EncodingFormat.NOCR: SB.Append('\n'); break; case EncodingFormat.NOCRLF: break; default: SB.Append("\r\n"); break; } return(SB.ToString()); }
private void TestExportRsaPrivateKey(EncodingFormat fmt) { using (var cp = GetCP()) { var pkp = new RsaPrivateKeyParams(); var pk = cp.GeneratePrivateKey(pkp); using (var target = new MemoryStream()) { cp.ExportPrivateKey(pk, fmt, target); } } }
public SpeechAudioFormatInfo(EncodingFormat encodingFormat, int samplesPerSecond, int bitsPerSample, int channelCount, int averageBytesPerSecond, int blockAlign, byte[] formatSpecificData) : this(encodingFormat, samplesPerSecond, (short)bitsPerSample, (short)channelCount, formatSpecificData) { if (averageBytesPerSecond <= 0) { throw new ArgumentOutOfRangeException("averageBytesPerSecond", SR.Get(SRID.MustBeGreaterThanZero)); } if (blockAlign <= 0) { throw new ArgumentOutOfRangeException("blockAlign", SR.Get(SRID.MustBeGreaterThanZero)); } _averageBytesPerSecond = averageBytesPerSecond; _blockAlign = (short)blockAlign; }
public WasapiRecorder(Stream stream, int sampleRate, int bitRate, int channels, EncodingFormat format, int preset) { if (stream == null) { throw new ArgumentNullException("stream"); } if (channels != 1 && channels != 2) { throw new ArgumentException(string.Format("Unsupported number of channels {0}", channels), "channels"); } if (bitRate != 16) { throw new ArgumentException(string.Format("Unsupported PCM sample size {0}", bitRate), "bitRate"); } if (sampleRate < 8000 || sampleRate > 48000) { throw new ArgumentException(string.Format("Unsupported Sample Rate {0}", sampleRate), "sampleRate"); } _stream = stream; _sampleRate = sampleRate; _bitRate = bitRate; _channels = channels; _format = format; _preset = preset; _capture = new AudioCapture(); _capture.SetCaptureFormat(_sampleRate, (ushort)_channels, (ushort)_bitRate); _size = 0; _duration = 0; _state = RecorderState.Unknown; if (_format == EncodingFormat.Wave) { _writer = new WaveWriter(_stream, _sampleRate, _bitRate, _channels); } else if (_format == EncodingFormat.MP3) { _writer = new Mp3Writer(_stream, _sampleRate, _bitRate, _channels, (LAMEPreset)_preset); } _timer = new DispatcherTimer(); _timer.Interval = TimeSpan.FromMilliseconds(33); _timer.Tick += OnSampleReceived; }
private void TestExportCertificate(EncodingFormat fmt, string filePath) { using (var cp = CertificateProvider.GetProvider()) { using (var source = new FileStream(filePath, FileMode.Open)) { var crt = cp.ImportCertificate(fmt, source); using (var target = new MemoryStream()) { cp.ExportCertificate(crt, fmt, target); } } } }
public SpeechAudioFormatInfo(EncodingFormat encodingFormat, int samplesPerSecond, int bitsPerSample, int channelCount, int averageBytesPerSecond, int blockAlign, byte[] formatSpecificData) : this(encodingFormat, samplesPerSecond, (short)bitsPerSample, (short)channelCount, formatSpecificData) { // Don't explicitly check these are sensible values - allow flexibility here as some formats may do unexpected things here. if (averageBytesPerSecond <= 0) { throw new ArgumentOutOfRangeException(nameof(averageBytesPerSecond), SR.Get(SRID.MustBeGreaterThanZero)); } if (blockAlign <= 0) { throw new ArgumentOutOfRangeException(nameof(blockAlign), SR.Get(SRID.MustBeGreaterThanZero)); } _averageBytesPerSecond = averageBytesPerSecond; _blockAlign = (short)blockAlign; }
/// <summary> /// Create a new virtual camera device from a <see cref="Stream"/>. /// </summary> /// <param name="stream">A video stream.</param> /// <param name="format">Image format used for encoding.</param> /// <param name="encodingParams">An array of parameters used for encoding.</param> public CameraVirtual(Stream stream, EncodingFormat format = EncodingFormat.PNG, Dictionary <ImwriteFlags, int> encodingParams = null) : base(format, encodingParams) { if (stream == null) { throw new NullReferenceException($"{nameof(stream)} cannot be null."); } FilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); using (var file = File.Create(FilePath)) stream.CopyTo(file); Capture = new VideoCapture(FilePath, api); hasTempFile = true; }
private SpeechAudioFormatInfo(EncodingFormat encodingFormat, int samplesPerSecond, short bitsPerSample, short channelCount, byte[] formatSpecificData) { if (encodingFormat == 0) { throw new ArgumentException(SR.Get(SRID.CannotUseCustomFormat), nameof(encodingFormat)); } if (samplesPerSecond <= 0) { throw new ArgumentOutOfRangeException(nameof(samplesPerSecond), SR.Get(SRID.MustBeGreaterThanZero)); } if (bitsPerSample <= 0) { throw new ArgumentOutOfRangeException(nameof(bitsPerSample), SR.Get(SRID.MustBeGreaterThanZero)); } if (channelCount <= 0) { throw new ArgumentOutOfRangeException(nameof(channelCount), SR.Get(SRID.MustBeGreaterThanZero)); } _encodingFormat = encodingFormat; _samplesPerSecond = samplesPerSecond; _bitsPerSample = bitsPerSample; _channelCount = channelCount; if (formatSpecificData == null) { _formatSpecificData = Array.Empty <byte>(); } else { _formatSpecificData = (byte[])formatSpecificData.Clone(); } switch (encodingFormat) { case EncodingFormat.ALaw: case EncodingFormat.ULaw: if (bitsPerSample != 8) { throw new ArgumentOutOfRangeException(nameof(bitsPerSample)); } if (formatSpecificData != null && formatSpecificData.Length != 0) { throw new ArgumentOutOfRangeException(nameof(formatSpecificData)); } break; } }
public override void ExportPrivateKey(PrivateKey pk, EncodingFormat fmt, Stream target) { var rsaPk = pk as CeRsaPrivateKey; if (rsaPk == null) { throw new NotSupportedException("unsupported private key type"); } var cePk = new CERTENROLLLib.CX509PrivateKey(); // MS_DEF_PROV //cePk.ProviderName = "Microsoft Base Cryptographic Provider"; cePk.ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"; // Don't store in the machine's local cert store and allow exporting of private key cePk.MachineContext = false; cePk.ExportPolicy = CERTENROLLLib.X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG; cePk.Import(BCRYPT_PRIVATE_KEY_BLOB, rsaPk.Exported); if (fmt == EncodingFormat.PEM) { var pem = cePk.Export(BCRYPT_PRIVATE_KEY_BLOB, CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BASE64HEADER); var pemBytes = Encoding.UTF8.GetBytes(pem); target.Write(pemBytes, 0, pemBytes.Length); } else if (fmt == EncodingFormat.DER) { // TODO: Verify this is DER, not quite sure var der = cePk.Export(BCRYPT_PRIVATE_KEY_BLOB, CERTENROLLLib.EncodingType.XCN_CRYPT_STRING_BINARY); var derBytes = new byte[der.Length]; for (int i = 0; i < derBytes.Length; ++i) { derBytes[i] = (byte)der[i]; } target.Write(derBytes, 0, derBytes.Length); } else { throw new NotSupportedException("unsupported encoding format"); } }
/// <summary> /// Support exporting CSR to <see cref="EncodingFormat.PEM">PEM</see> format. /// </summary> public override void ExportPrivateKey(PrivateKey pk, EncodingFormat fmt, Stream target) { var rsaPk = pk as RsaPrivateKey; if (rsaPk == null) { throw new NotSupportedException("unsupported private key type"); } if (fmt == EncodingFormat.PEM) { var bytes = Encoding.UTF8.GetBytes(rsaPk.Pem); target.Write(bytes, 0, bytes.Length); } else { throw new NotSupportedException("unsupported encoding format"); } }
public static void ExportPrivateKey(CertPrivateKey pk, EncodingFormat fmt, Stream target) { switch (fmt) { case EncodingFormat.PEM: var pem = ToPrivatePem(pk.KeyPair); var bytes = Encoding.UTF8.GetBytes(pem); target.Write(bytes, 0, bytes.Length); break; case EncodingFormat.DER: var der = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pk.KeyPair.Private).GetDerEncoded(); target.Write(der, 0, der.Length); break; default: throw new NotSupportedException("unsupported encoding format"); } }
/// <summary> /// Supports importing certificates from <see cref="EncodingFormat.PEM">PEM</see> /// and <see cref="EncodingFormat.DER">DER</see> formats. /// </summary> public override Crt ImportCertificate(EncodingFormat fmt, Stream source) { if (fmt == EncodingFormat.DER) { using (var ms = new MemoryStream()) { source.CopyTo(ms); using (var bio = BIO.MemoryBuffer()) { bio.Write(ms.ToArray()); using (var x509 = X509Certificate.FromDER(bio)) { return(new Crt { Pem = x509.PEM }); } } } } else if (fmt == EncodingFormat.PEM) { using (var r = new StreamReader(source)) { using (var bio = BIO.MemoryBuffer()) { bio.Write(r.ReadToEnd()); using (var x509 = new X509Certificate(bio)) { return(new Crt { Pem = x509.PEM }); } } } } else { throw new NotSupportedException("encoding format has not been implemented"); } }
private SpeechAudioFormatInfo(EncodingFormat encodingFormat, int samplesPerSecond, short bitsPerSample, short channelCount, byte[] formatSpecificData) { if (encodingFormat == (EncodingFormat)0) { throw new ArgumentException(SR.Get(SRID.CannotUseCustomFormat), "encodingFormat"); } if (samplesPerSecond <= 0) { throw new ArgumentOutOfRangeException("samplesPerSecond", SR.Get(SRID.MustBeGreaterThanZero)); } if (bitsPerSample <= 0) { throw new ArgumentOutOfRangeException("bitsPerSample", SR.Get(SRID.MustBeGreaterThanZero)); } if (channelCount <= 0) { throw new ArgumentOutOfRangeException("channelCount", SR.Get(SRID.MustBeGreaterThanZero)); } _encodingFormat = encodingFormat; _samplesPerSecond = samplesPerSecond; _bitsPerSample = bitsPerSample; _channelCount = channelCount; if (formatSpecificData == null) { _formatSpecificData = new byte[0]; } else { _formatSpecificData = (byte[])formatSpecificData.Clone(); } if ((uint)(encodingFormat - 6) <= 1u) { if (bitsPerSample != 8) { throw new ArgumentOutOfRangeException("bitsPerSample"); } if (formatSpecificData != null && formatSpecificData.Length != 0) { throw new ArgumentOutOfRangeException("formatSpecificData"); } } }
public override Crt ImportCertificate(EncodingFormat fmt, Stream source) { if (fmt == EncodingFormat.DER) { var x509 = new X509Certificate2(); using (var ms = new MemoryStream()) { source.CopyTo(ms); x509.Import(ms.ToArray()); } var crt = new Crt { Pem = Convert.ToBase64String(x509.RawData), }; return(crt); } throw new NotSupportedException("unsupported encoding format"); }
private void TestImportRsaCsr(EncodingFormat fmt) { using (var cp = CertificateProvider.GetProvider()) { var pkp = new RsaPrivateKeyParams(); var pk = cp.GeneratePrivateKey(pkp); var crp = new CsrParams { Details = new CsrDetails { CommonName = "TEST CERT", } }; var csr = cp.GenerateCsr(crp, pk, Crt.MessageDigest.SHA256); byte[] bytes; using (var target = new MemoryStream()) { cp.ExportCsr(csr, fmt, target); bytes = target.ToArray(); } var imp = csr; using (var source = new MemoryStream(bytes)) { imp = cp.ImportCsr(fmt, source); } using (MemoryStream save1 = new MemoryStream(), save2 = new MemoryStream()) { cp.SaveCsr(csr, save1); cp.SaveCsr(imp, save2); var bytes1 = save1.ToArray(); var bytes2 = save2.ToArray(); CollectionAssert.AreEqual(bytes1, bytes2); } } }
private void TestExportRsaCsr(EncodingFormat fmt) { using (var cp = CertificateProvider.GetProvider()) { var pkp = new RsaPrivateKeyParams(); var pk = cp.GeneratePrivateKey(pkp); var crp = new CsrParams { Details = new CsrDetails { CommonName = "TEST CERT", } }; var csr = cp.GenerateCsr(crp, pk, Crt.MessageDigest.SHA256); using (var target = new MemoryStream()) { cp.ExportCsr(csr, fmt, target); } } }
private string DecodePartialVFPURegister(EncodingFormat encFormat, uint line, int regIndex, char lookupChar) { string formatBinary = encFormat.Binary; string newFormat = encFormat.ExpandedFormat; /* int[] binaryIndex = new int[2]; int part1Index = formatBinary.IndexOf("[p" + (regIndex + 1).ToString() + "-1"); int part2Index = formatBinary.IndexOf("[p" + (regIndex + 1).ToString() + "-2"); int firstIndex = newFormat.IndexOf(lookupChar); int searchPartIndex = firstIndex; for (; newFormat[searchPartIndex] == lookupChar; searchPartIndex++) ; int secondIndex = newFormat.IndexOf(lookupChar, searchPartIndex); if (part1Index > part2Index) { binaryIndex[0] = secondIndex; binaryIndex[1] = firstIndex; } else { binaryIndex[0] = firstIndex; binaryIndex[1] = secondIndex; } */ //string firstValue = binaryLine.Substring(binaryIndex[0], encFormat.PartialRegisterSizes[0]); //string secondValue = binaryLine.Substring(binaryIndex[1], encFormat.PartialRegisterSizes[1]); //int firstValue = FindNumericArgValue(line, encFormat.PartialRegisterPositions[regIndex][0], ASMValueHelper.GetIncludeMask(encFormat.PartialRegisterSizes[0])); //int secondValue = FindNumericArgValue(line, encFormat.PartialRegisterPositions[regIndex][1], ASMValueHelper.GetIncludeMask(encFormat.PartialRegisterSizes[1])); int firstValue = FindNumericArgValue(line, encFormat.PartialRegisterPositions[regIndex][0], encFormat.PartialRegisterIncludeMasks[regIndex][0]); int secondValue = FindNumericArgValue(line, encFormat.PartialRegisterPositions[regIndex][1], encFormat.PartialRegisterIncludeMasks[regIndex][1]); //string binaryValue = firstValue + secondValue; int totalValue = (firstValue << encFormat.PartialRegisterSizes[1]) + secondValue; string argValue = DecodeRegister(totalValue, ASMElementTypeCharacter.PartialVFPURegister, false, encFormat.VFPURegisterTypes[regIndex]); return argValue; }
internal string Encode(string input, EncodingFormat format) { str_rle = null; str_base = input; if (format == EncodingFormat.New) { for (int i = 0; i < str_base.Length; i++) { char symbol = str_base[i]; int count = 1; for (int j = i; j < str_base.Length - 1; j++) { if (str_base[j + 1] != symbol) break; count++; i++; } if (count == 1) str_rle += symbol; else str_rle += count.ToString() + symbol; } } else if (format == EncodingFormat.Old) { for (int i = 0; i < str_base.Length; i++) { char symbol = str_base[i]; int count = 1; for (int j = i; j < str_base.Length - 1; j++) { if (str_base[j + 1] != symbol) break; count++; i++; } str_rle += count.ToString() + symbol; } } return str_rle; }
internal string Encode(EncodingFormat encodingFormat) { using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(ms)) { if (this.checksum != null) { writer.Write((byte)(encodingFormat | EncodingFormat.Checksum)); SymbolHelper.WriteEncodedInt32(writer, this.checksum.Length); writer.Write(this.checksum); } else { writer.Write((byte)encodingFormat); } switch (encodingFormat) { case EncodingFormat.Binary: this.Write(writer); break; case EncodingFormat.String: writer.Write(this.ToString()); break; default: throw FxTrace.Exception.AsError(new SerializationException()); } // Need to copy to a buffer to trim excess capacity. byte[] buffer = new byte[ms.Length]; Array.Copy(ms.GetBuffer(), buffer, ms.Length); return Convert.ToBase64String(buffer); } } }
private ASMSingleEncodeResult TryEncodeSingle(string[] parts, EncodingFormat encoding, uint pc, string processLine, bool littleEndian) { try { return EncodeASMSingle(parts, encoding, pc, littleEndian); } catch (Exception ex) { _errorTextBuilder.Append("FAILED TO ENCODE LINE : "); _errorTextBuilder.Append(processLine); _errorTextBuilder.Append(" ("); _errorTextBuilder.Append(ex.Message); _errorTextBuilder.Append(")"); _errorTextBuilder.Append("\r\n"); return new ASMSingleEncodeResult("", new List<byte>().ToArray()); } }
private byte[] EncodeASMSingle(string[] parts, EncodingFormat encoding, int pc) { // Initialize variables string binary = encoding.format.Substring(0); string hex = ""; string strArgs = ""; string[] args = null; if (!string.IsNullOrEmpty(parts[1])) { strArgs = RemoveSpaces(parts[1]); args = strArgs.Split(','); } int immed = 0; int difference = 0; string hexImmed = ""; string binaryImmed = ""; int startParenIndex = 0; int endParenIndex = 0; string strImmed = ""; string regS = ""; // (1) -- Encode MIPS instruction in BINARY -- // I've defined 17 types of MIPS instructions based on R/I/J type as well as order // of arguments (rd,rs,rt and rd,rt,rs would be two different types) // (See mips_encode.dat: Format is: [ command : type : encoding ]) // For each type, determine what in the encoding is variable, and replace it with the properly // encoded argument (register or immediate). switch (encoding.type) { case 1: // R-type register-only operations: rd,rs,rt (add,and,or,sub,subu,slt,etc) binary = binary.Replace("d", EncodeRegister(args[0])); binary = binary.Replace("s", EncodeRegister(args[1])); binary = binary.Replace("t", EncodeRegister(args[2])); break; case 2: // I-type conditional branches on register values: rs,rt,[immediate] (beq,bne) if (args[2].StartsWith("0x")) { if (args[2].Length >= 10) immed = HexToUnsigned(args[2].Substring(3,args[2].Length-3)); else immed = HexToUnsigned(args[2].Substring(2,args[2].Length-2)); } else if (StringIsNumeric(args[2])) { immed = Convert.ToInt32(args[2]); } else { immed = LabelToUnsigned(args[2]); } difference = (immed - pc - 4) / 4; hexImmed = SignedToHex_WithLength(difference, 4); binaryImmed = HexHalfWordToBinary(hexImmed); binary = binary.Replace("s", EncodeRegister(args[0])); binary = binary.Replace("t", EncodeRegister(args[1])); binary = binary.Replace("i", binaryImmed); break; case 3: // I-type operations with immediates: rt,rs,[immediate] (addi,addiu,andi,ori,xori,slti,sltiu) case 17: binary = binary.Replace("t", EncodeRegister(args[0])); binary = binary.Replace("s", EncodeRegister(args[1])); binary = binary.Replace("i", EncodeImmediateHalfWord(args[2])); break; case 4: // I-type conditional branches on register value vs. fixed value: rs,[immediate] (bgez,bgtz,blez,bltz) if (args[1].StartsWith("0x")) { if (args[1].Length >= 10) immed = HexToUnsigned(args[1].Substring(3,args[1].Length-3)); else immed = HexToUnsigned(args[1].Substring(2,args[1].Length-2)); } else if (StringIsNumeric(args[1])) { immed = Convert.ToInt32(args[1]); } else { immed = LabelToUnsigned(args[1]); } difference = (immed - pc - 4) / 4; hexImmed = SignedToHex_WithLength(difference, 4); binaryImmed = HexHalfWordToBinary(hexImmed); binary = binary.Replace("s", EncodeRegister(args[0])); binary = binary.Replace("i", binaryImmed); break; case 5: // R-type operations using HI/LO as destination registers: rs,rt (mult,multu,div,divu) binary = binary.Replace("s", EncodeRegister(args[0])); binary = binary.Replace("t", EncodeRegister(args[1])); break; case 6: // J-type unconditional jumps to address specified by long immediate: [immediate] (j,jal) binary = binary.Replace("i", EncodeLongImmediate(args[0], 8)); break; case 7: // R-type instructions with only one argument: rs (jr,mthi,mtlo) binary = binary.Replace("s", EncodeRegister(args[0])); break; case 8: // I-type memory operations: rt, [immediate](rs) (lb,lbu,lh,lhu,lw,sb,sh,sw) startParenIndex = args[1].IndexOf('('); endParenIndex = args[1].IndexOf(')'); strImmed = args[1].Substring(0,startParenIndex); regS = args[1].Substring(startParenIndex+1, endParenIndex-startParenIndex-1); binary = binary.Replace("t", EncodeRegister(args[0])); binary = binary.Replace("s", EncodeRegister(regS)); binary = binary.Replace("i", EncodeImmediateHalfWord(strImmed)); break; case 9: // I-type operations loading immediates into registers: rt, [immediate] (lui) binary = binary.Replace("t", EncodeRegister(args[0])); binary = binary.Replace("i", EncodeImmediateHalfWord(args[1])); break; case 10: // R-type moves from HI/LO to a destination register: rd (mfhi,mflo) binary = binary.Replace("d", EncodeRegister(args[0])); break; case 11: // R-type operations with no arguments (syscall,nop) break; case 12: // R-type shift operations using [shamt] as shift amount: rd,rt,[shamt] (sll,srl,sra) binary = binary.Replace("d", EncodeRegister(args[0])); binary = binary.Replace("t", EncodeRegister(args[1])); binary = binary.Replace("h", EncodeShiftAmount(args[2])); break; case 13: // R-type shift operations using register value as shift amount: rd,rt,rs (sllv,srlv) binary = binary.Replace("d", EncodeRegister(args[0])); binary = binary.Replace("t", EncodeRegister(args[1])); binary = binary.Replace("s", EncodeRegister(args[2])); break; case 14: // R-type or I-type operations using only one operand and a destination register: rt,rs (not,move) binary = binary.Replace("t", EncodeRegister(args[0])); binary = binary.Replace("s", EncodeRegister(args[1])); break; case 15: // R-type opreations with 10-bit immediate (syscall, break) binary = binary.Replace("i", EncodeImmediate(args[0], 10)); break; case 16: // J-type operations with 26-bit immediate, not using jump-encoding (trap) binary = binary.Replace("i", EncodeImmediate(args[0], 26)); break; default: break; } // (2) -- Translate BINARY to HEX -- hex = BinaryWordToHex_LittleEndian(binary); // (3) -- Translate HEX to BYTE LIST -- List<Byte> result = new List<Byte>(); result.Add(Convert.ToByte(hex.Substring(0,2),16)); result.Add(Convert.ToByte(hex.Substring(2,2),16)); result.Add(Convert.ToByte(hex.Substring(4,2),16)); result.Add(Convert.ToByte(hex.Substring(6,2),16)); return result.ToArray(); }
private ASMSingleEncodeResult EncodeASMSingle(string[] parts, EncodingFormat encoding, uint pc, bool littleEndian) { // Initialize variables //string binary = ""; //string hex = ""; string strArgs = ""; string[] args = null; /* if (!string.IsNullOrEmpty(parts[1])) { strArgs = ASMStringHelper.RemoveSpaces(parts[1]).Replace('(',',').Replace(")",""); args = strArgs.Split(','); } */ // Find encoding format and syntax string command = parts[0].ToLower(); EncodingFormat encodingFormat = FormatHelper.FindFormatByCommand(command); string formatBinary = encodingFormat.Binary; string syntax = encodingFormat.Syntax; string newFormat = formatBinary; if (!string.IsNullOrEmpty(parts[1])) { List<string> argsList = new List<string>(); strArgs = ASMStringHelper.RemoveSpaces(parts[1]); bool foundArg = false; int strArgCharIndex = 0; foreach (char currentChar in syntax) { if (Char.IsLetter(currentChar)) { foundArg = true; } else if (foundArg) { foundArg = false; bool isHiLo = ((strArgs.IndexOf("%hi(", strArgCharIndex) == strArgCharIndex) || (strArgs.IndexOf("%lo(", strArgCharIndex) == strArgCharIndex)); int separatorIndex = strArgs.IndexOf(currentChar, strArgCharIndex + (isHiLo ? 4 : 0)); argsList.Add(strArgs.Substring(strArgCharIndex, separatorIndex - strArgCharIndex)); strArgCharIndex = separatorIndex + 1; } } if (foundArg) { argsList.Add(strArgs.Substring(strArgCharIndex, strArgs.Length - strArgCharIndex)); } args = argsList.ToArray(); } // Create array for registers and immediates Nullable<uint>[] regValue = new Nullable<uint>[26]; Nullable<uint>[][] partialRegValue = new Nullable<uint>[26][]; uint[] immedValue = new uint[26]; int argsIndex = 0; int regIndex = 0; int immedIndex = 0; // Fill arrays based on order of arguments (syntax) foreach (char elementTypeChar in syntax) { bool incrementArgsIndex = true; switch (elementTypeChar) { case ASMElementTypeCharacter.GPRegister: regValue[regIndex++] = EncodeGPRegister(args[argsIndex]); break; case ASMElementTypeCharacter.GenericRegister: regValue[regIndex++] = EncodeGenericRegister(args[argsIndex]); break; case ASMElementTypeCharacter.FloatRegister: regValue[regIndex++] = EncodeFloatRegister(args[argsIndex]); break; case ASMElementTypeCharacter.VFPURegister: regValue[regIndex] = EncodeVFPURegister(args[argsIndex], encodingFormat.VFPURegisterTypes[regIndex]); regIndex++; break; case ASMElementTypeCharacter.PartialVFPURegister: partialRegValue[regIndex] = EncodePartialVFPURegister(args[argsIndex], encodingFormat.VFPURegisterTypes[regIndex], encodingFormat.PartialRegisterSizes, encodingFormat.PartialRegisterIncludeMasks[regIndex]); regIndex++; break; case ASMElementTypeCharacter.InvertedSingleBitVFPURegister: regValue[regIndex] = EncodeInvertedSingleBitVFPURegister(args[argsIndex], encodingFormat.VFPURegisterTypes[regIndex]); regIndex++; break; case ASMElementTypeCharacter.Cop0Register: regValue[regIndex] = EncodeCop0Register(args[argsIndex]); regIndex++; break; case ASMElementTypeCharacter.GTEControlRegister: regValue[regIndex] = EncodeGTEControlRegister(args[argsIndex]); regIndex++; break; case ASMElementTypeCharacter.GTEDataRegister: regValue[regIndex] = EncodeGTEDataRegister(args[argsIndex]); regIndex++; break; case ASMElementTypeCharacter.SignedImmediate: case ASMElementTypeCharacter.UnsignedImmediate: immedValue[immedIndex] = EncodeImmediate(args[argsIndex], encodingFormat.ImmediateLengths[immedIndex], (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.BranchImmediate: immedValue[immedIndex] = EncodeBranchImmediate(args[argsIndex], pc, (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.JumpImmediate: immedValue[immedIndex] = EncodeJumpImmediate(args[argsIndex], 26, pc); immedIndex++; break; case ASMElementTypeCharacter.DecrementedImmediate: immedValue[immedIndex] = EncodeDecrementedImmediate(args[argsIndex], encodingFormat.ImmediateLengths[immedIndex], (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.ModifiedImmediate: immedValue[immedIndex] = EncodeModifiedImmediate(args[argsIndex], args[argsIndex - 1], encodingFormat.ImmediateLengths[immedIndex], (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.ShiftedImmediate: immedValue[immedIndex] = EncodeShiftedImmediate(args[argsIndex], encodingFormat.ImmediateLengths[immedIndex], encodingFormat.ShiftedImmediateAmounts[immedIndex], (uint)encodingFormat.ImmediateIncludeMasks[immedIndex]); immedIndex++; break; case ASMElementTypeCharacter.VFPUPrefixImmediate: immedValue[immedIndex] = EncodeVFPUPrefixImmediate(args[argsIndex], encodingFormat.VFPUPrefixType, encodingFormat.ImmediateLengths[immedIndex]); immedIndex++; break; default: incrementArgsIndex = false; break; } if (incrementArgsIndex) argsIndex++; } /* // Replace bracket blocks in format with appropriate values for (int i = 0; i < regIndex; i++) { newFormat = newFormat.Replace("[" + encodingFormat.RegisterTypes[i] + (i + 1) + "]", regBinary[i]); if (partialRegBinary[i] != null) { newFormat = newFormat.Replace("[" + encodingFormat.RegisterTypes[i] + (i + 1) + "-1]", partialRegBinary[i][0]); newFormat = newFormat.Replace("[" + encodingFormat.RegisterTypes[i] + (i + 1) + "-2]", partialRegBinary[i][1]); } } for (int i = 0; i < immedIndex; i++) { newFormat = newFormat.Replace("[" + encodingFormat.ImmediateTypes[i] + (i + 1) + "]", immedBinary[i]); } binary = newFormat; */ uint uEncodingValue = encodingFormat.BaseEncoding; for (int i = 0; i < regIndex; i++) { if (regValue[i] != null) { uEncodingValue |= (((uint)regValue[i]) << encodingFormat.RegisterPositions[i]); } else if (partialRegValue[i] != null) { uEncodingValue |= (((uint)partialRegValue[i][0]) << encodingFormat.PartialRegisterPositions[i][0]); uEncodingValue |= (((uint)partialRegValue[i][1]) << encodingFormat.PartialRegisterPositions[i][1]); } } for (int i = 0; i < immedIndex; i++) { uEncodingValue |= (immedValue[i] << encodingFormat.ImmediatePositions[i]); } //byte[] bytes = BitConverter.GetBytes(uEncodingValue); byte[] bytes = ASMValueHelper.ConvertUIntToBytes(uEncodingValue, littleEndian); if (littleEndian) { uEncodingValue = ASMValueHelper.ReverseBytes(uEncodingValue); } //else //{ // Array.Reverse(bytes); //} string hex = ASMValueHelper.UnsignedToHex_WithLength(uEncodingValue, 8).ToUpper(); return new ASMSingleEncodeResult(hex, bytes); }
private static WaveFormatEncoding GetWaveEncodingFormat(EncodingFormat encoding) { switch (encoding) { case EncodingFormat.Pcm: return WaveFormatEncoding.LPCM; default: return WaveFormatEncoding.Unknown; } }
// For reading mips_encode.dat public void ReadEncodeList() { StreamReader reader = new StreamReader("mips_encode.dat"); try { while(reader.Peek() != -1) { string line = reader.ReadLine(); line = RemoveSpaces(line); string[] lineArray = line.Split(':'); EncodingFormat encoding = new EncodingFormat(); encoding.command = lineArray[0]; encoding.type = Convert.ToInt32(lineArray[1]); encoding.format = lineArray[2]; encodeList.Add(encoding); } } catch { } finally { reader.Close(); } }