public bool TryReadTextString(Span <char> destination, out int charsWritten) { CborInitialByte header = PeekInitialByte(expectedType: CborMajorType.TextString); if (header.AdditionalInfo == CborAdditionalInfo.IndefiniteLength) { return(TryReadChunkedTextStringConcatenated(destination, out charsWritten)); } int byteLength = checked ((int)ReadUnsignedInteger(_buffer.Span, header, out int additionalBytes)); EnsureBuffer(1 + additionalBytes + byteLength); ReadOnlySpan <byte> encodedSlice = _buffer.Span.Slice(1 + additionalBytes, byteLength); int charLength = ValidateUtf8AndGetCharCount(encodedSlice); if (charLength > destination.Length) { charsWritten = 0; return(false); } s_utf8Encoding.GetChars(encodedSlice, destination); AdvanceBuffer(1 + additionalBytes + byteLength); AdvanceDataItemCounters(); charsWritten = charLength; return(true); }
private char[]/*!*/ DataToChars(int additionalCapacity, Encoding/*!*/ encoding) { if (_count == 0) { return (additionalCapacity == 0) ? Utils.EmptyChars : new char[additionalCapacity]; } else if (additionalCapacity == 0) { return encoding.GetChars(_data, 0, _count); } else { var result = new char[encoding.GetCharCount(_data, 0, _count) + additionalCapacity]; encoding.GetChars(_data, 0, _count, result, 0); return result; } }
public ArrayInstance GetChars(object a) { if (a is String || a is ConcatenatedString) { return(encoding.GetChars(encoding.GetBytes(a.ToString())).ToJSArray(Engine)); } else if (a is ArrayInstance) { return(encoding.GetChars(((ArrayInstance)a).ToArray <byte>(encoding)).ToJSArray(Engine)); } return(null); }
public static string ToTrimmedString(byte[] buffer, Encoding encoding) { var encoded = encoding.GetChars(buffer); var i = 0; while (i < encoded.Length && encoded[i] != 0) i++; return encoding.GetString(encoding.GetBytes(encoded.Take(i).ToArray())); }
/// <summary> /// Appends the <paramref name="password"/> byte array to the end of the current <see cref="System.Security.SecureString"/>. /// </summary> /// <param name="secureStr">This <see cref="System.Security.SecureString"/>.</param> /// <param name="password">The byte array to append to the end of the current <see cref="System.Security.SecureString"/>.</param> /// <param name="encoder">The <see cref="System.Text.Encoding"/> used to encode the string into a byte array.</param> /// <param name="autoClearIncomingByteArray">If <b>true</b>, will automatically clear the contents of the incoming byte array; <b>false</b>, will leave the contents of the incoming byte array as is.</param> /// <remarks> /// <para> /// <b>Important:</b> It is incumbent on the developer using this function to clear the incoming byte array after using it. /// Otherwise, it will contain the characters of the password (as bytes) in the clear and it will remain in memory until the garbage collector frees the memory and the memory is overwritten. /// Also note, the garbage collector freeing the memory does not clear the memory; the memory will remain as is until it is allocated and written over. See <see cref="Array.Clear"/> for more information. /// </para> /// </remarks> /// <returns>A <see cref="System.Security.SecureString"/> populated with the <paramref name="password"/>.</returns> public static System.Security.SecureString AppendBytes(this System.Security.SecureString secureStr, byte[] password, System.Text.Encoding encoder, bool autoClearIncomingByteArray) { if ((password == null) || (password.Length == 0)) { throw new ArgumentNullException("password"); } if (encoder == null) { throw new ArgumentNullException("encoder"); } char[] worker = null; try { worker = encoder.GetChars(password); foreach (var ch in worker) { secureStr.AppendChar(ch); } } finally { if (worker != null) { Array.Clear(worker, 0, worker.Length); } if (autoClearIncomingByteArray) { Array.Clear(password, 0, password.Length); } } return(secureStr); }
public virtual char[] GetChars(byte[] bytes, int index, int count) { CheckParams(bytes, index, count); if (IsSingleByte) { return(encoding.GetChars(bytes, index, count)); } if (count == 0) { return(new char[0]); } char[] ret = new char[GetCharCount(bytes, index, count)]; --count; var dec = GetDecoder(); int conv1 = dec.GetChars(bytes, index, count, ret, 0); int conv2 = dec.GetChars(bytes, index + count, 1, ret, conv1); if (conv2 != 1 || (conv1 + conv2) != ret.Length) { throw new DecoderFallbackException(); } return(ret); }
public static unsafe FFXIIICodePage Create(Encoding encoding) { byte[] buff = new byte[256]; char[] chars = new char[256 + 0x2C10]; fixed (byte* buffPtr = &buff[0]) fixed (char* charsPtr = &chars[0]) { for (int b = 0; b < 256; b++) buffPtr[b] = (byte)b; encoding.GetChars(buffPtr, buff.Length, charsPtr, buff.Length); } CreateAdditionalCharacters(chars); Dictionary<char, short> bytes = new Dictionary<char, short>(chars.Length); for (int i = chars.Length - 1; i >= 0; i--) { char ch = chars[i]; switch (ch) { case '\0': continue; } bytes[chars[i]] = (short)i; } return new FFXIIICodePage(chars, bytes); }
public static char[] CompressToChar(char[] str, bool needheadflag, Encoding enc) { if (str.Length < zipsizemin) return str; Byte[] bTytes = enc.GetBytes(str); Byte[] retbytes = Compress(bTytes, needheadflag, enc); return enc.GetChars(retbytes); }
public string ReadPort() { System.Text.Encoding Encoding = System.Text.Encoding.UTF8; byte[] readBuffer = new byte[2049]; int readLength = 0; int Result = readcd722usb(ref readBuffer[0], readLength); return(new string(Encoding.GetChars(readBuffer, 0, readLength))); }
private void TestEncoding(Encoding enc, int byteCount, int maxByteCount, byte[] bytes) { Assert.Equal(byteCount, enc.GetByteCount(s_myChars)); Assert.Equal(maxByteCount, enc.GetMaxByteCount(s_myChars.Length)); Assert.Equal(enc.GetBytes(s_myChars), bytes); Assert.Equal(enc.GetCharCount(bytes), s_myChars.Length); Assert.Equal(enc.GetChars(bytes), s_myChars); Assert.Equal(enc.GetString(bytes, 0, bytes.Length), s_myString); Assert.NotEqual(0, enc.GetHashCode()); }
//Перекодирует value из кодировки encoder в кодировку decoder public string Decode(Encoding encoder, Encoding decoder, string value) { byte[] intByteBuff, charBuff, outByteBuff, codeBytes; char[] chars; codeBytes = new byte[encoder.GetByteCount(value)]; encoder.GetBytes(value, 0, value.Length, codeBytes, 0); chars = decoder.GetChars(codeBytes); return new string(chars); }
static void issueResponseB(ref byte[] boater, Int32 len) { System.Text.Encoding utf8_encoding = System.Text.Encoding.UTF8; int elts = boater.Length; Console.WriteLine("Boater length: {0}", elts); Console.Out.Flush(); string s = new string(utf8_encoding.GetChars(boater, 0, len)); Console.WriteLine("{0}", s); }
public string ReadString(int length, Encoding enc) { byte[] buf=new byte[length]; int amountRead=Read(buf, 0, length); if ( amountRead != length ) throw new InvalidOperationException("End of file while reading a string"); char[] chars=enc.GetChars(buf); return new string(chars); }
private string ReEncode( System.Text.Encoding fromEncoding, System.Text.Encoding toEncoding, string text) { byte[] frombyte = fromEncoding.GetBytes(text); byte[] tobyte = Encoding.Convert(fromEncoding, toEncoding, frombyte); char[] tochar = new char[toEncoding.GetCharCount(tobyte, 0, tobyte.Length)]; toEncoding.GetChars(tobyte, 0, tobyte.Length, tochar, 0); string tostr = new string(tochar); return(tostr); }
public static String ToEncoding(this String psValue, Encoding poSourceEncoding, Encoding poDestinationEncoding) { if (String.IsNullOrEmpty(psValue)) { return psValue; } var loSourceBytes = poSourceEncoding.GetBytes(psValue); var loDestinationBytes = Encoding.Convert(poSourceEncoding, poDestinationEncoding, loSourceBytes); var loDestinationChars = new char[poDestinationEncoding.GetCharCount(loDestinationBytes, 0, loDestinationBytes.Length)]; poDestinationEncoding.GetChars(loDestinationBytes, 0, loDestinationChars.Length, loDestinationChars, 0); return new string(loDestinationChars); }
public static string ConvertAsciiToUtf8(string asciiString) { System.Text.Encoding ascii = System.Text.Encoding.ASCII; System.Text.Encoding utf8 = System.Text.Encoding.UTF8; byte[] asciiBytes = ascii.GetBytes(asciiString); byte[] utf8Bytes = System.Text.Encoding.Convert(ascii, utf8, asciiBytes); char[] utf8Chars = new char[utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length)]; utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0); string utf8String = new string(utf8Chars); return(utf8String); }
private static void ConvertEncoding(Encoding unicode, Encoding ascii) { string storyline = "Cobb's rare ability"; var sourceBytes = ascii.GetBytes(storyline); var destBytes = Encoding.Convert(ascii, unicode, sourceBytes); var destChars = new char[unicode.GetCharCount(destBytes, 0, destBytes.Length)]; unicode.GetChars(destBytes, 0, destBytes.Length, destChars, 0); var newString = new string(destChars); Console.WriteLine("\n-------------------------------"); Console.WriteLine(DateTime.Now); Console.WriteLine(unicode.EncodingName); Console.WriteLine(ascii.EncodingName); Console.WriteLine("==============================="); Console.WriteLine(newString); }
//============ // 指定コードバイト型配列 ---> ユニコードstring 変換メソッド // // 内容: 指定コード(例: シフトJISコード)のバイト型配列をユニコードの文字列に変換する。 // // 第1引数: 変換前の文字列を入力指定(byte型配列のシフトJISコードの文字列) // 第2引数: 変換前のエンコードを入力指定(シフトJISコード時は、"shift_jis") // 第3引数: 変換後の文字列を出力(string型のユニコードの文字列) // // 戻り値: エラー情報(0から1: 成功、2以上: 失敗) // _______________(1: 警告(フォールバック発生)) // // エンコーディングを示すコードページ名(第2引数指定値) // シフトJIS: "shift_jis" // JIS: "iso-2022-jp" // 日本語EUC: "euc-jp" // Unicode (UTF-8): "utf-8" public static int ChangeBinaryToUnicodeStr(byte[] BeforeBytes, string BeforeEncod, out string UnicodeText) { // 初期化 UnicodeText = ""; int ErrorInfo = 0; // エラー情報 // 入力がnull時のエラー処理 if (BeforeBytes == null || BeforeEncod == null) { return(2); } // 文字コードを示すエンコードを生成 System.Text.Encoding AfterEncodObj = System.Text.Encoding.Unicode; // 変換後エンコード System.Text.Encoding BeforeEncodObj = System.Text.Encoding.GetEncoding(BeforeEncod); // 変換前エンコード // 指定コードをユニコードに変換 byte[] AfterBytes = null; try { AfterBytes = System.Text.Encoding.Convert(BeforeEncodObj, AfterEncodObj, BeforeBytes); } catch (DecoderFallbackException) { // フォールバックが発生 ErrorInfo = 1; } catch (EncoderFallbackException) { // フォールバックが発生 ErrorInfo = 1; } catch (ArgumentNullException) { // 入出力文字列格納用オブジェクト または encoding が null を参照し、失敗 ErrorInfo = 2; } // バイト型配列のユニコード文字列をstring型に設定 char[] AfterChars = new char[AfterEncodObj.GetCharCount(AfterBytes, 0, AfterBytes.Length)]; AfterEncodObj.GetChars(AfterBytes, 0, AfterBytes.Length, AfterChars, 0); UnicodeText = new string(AfterChars); return(ErrorInfo); }
/// <summary> /// This method returns a null-terminated string from the buffer using /// a specific text encoding type. /// </summary> /// <param name="encoder">Text encoder to use for decode</param> /// <returns>String without null</returns> public string ReadString(System.Text.Encoding encoder) { // Read until we either hit the end of the buffer, or a NULL. byte[] oneByte = new byte[1]; StringBuilder sb = new StringBuilder(); int ch = _stream.ReadByte(); while (ch > 0) { oneByte[0] = (byte)ch; sb.Append(encoder.GetChars(oneByte)); ch = _stream.ReadByte(); } // Return the built string. return(sb.ToString()); }
// Convert between two encodings. public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes) { if(srcEncoding == null) { throw new ArgumentNullException("srcEncoding"); } if(dstEncoding == null) { throw new ArgumentNullException("dstEncoding"); } if(bytes == null) { throw new ArgumentNullException("bytes"); } return dstEncoding.GetBytes(srcEncoding.GetChars (bytes, 0, bytes.Length)); }
private JsEncoder.IAbstractValue[] Encoding_CollectOutput() { // Receive Bytes int NumberOfBytes = _Socket.Available; byte[] EncodedBytes = new byte[NumberOfBytes]; if (NumberOfBytes > 0) { _Socket.Client.Receive(EncodedBytes); } // Decode Data char[] EncodedChars = _EncodingFormat.GetChars(EncodedBytes); string EncodedString = new string(EncodedChars); _Decoder.InputValue(EncodedString); _Decoder.RunParser(); return(_Decoder.PopOutput()); }
public string ConvertLayoutInfoToString(LayoutInfo info) { string result = String.Empty; Microsoft.VisualStudio.Modeling.SerializationResult serializationResult = new Microsoft.VisualStudio.Modeling.SerializationResult(); DomainXmlSerializerDirectory directory = this.GetDirectory(info.Store); System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("ISO-8859-1"); Microsoft.VisualStudio.Modeling.SerializationContext serializationContext = new SerializationContext(directory, "", serializationResult); this.InitializeSerializationContext(info.Partition, serializationContext, false); global::System.IO.MemoryStream newFileContent = new global::System.IO.MemoryStream(); global::System.Xml.XmlWriterSettings settings = DiagramsDSLSerializationHelper.Instance.CreateXmlWriterSettings(serializationContext, false, encoding); using (global::System.Xml.XmlWriter writer = global::System.Xml.XmlWriter.Create(newFileContent, settings)) { DomainClassXmlSerializer rootSerializer = directory.GetSerializer(LayoutInfo.DomainClassId); RootElementSettings rootElementSettings = new RootElementSettings(); rootElementSettings.SchemaTargetNamespace = "http://schemas.microsoft.com/dsltools/DiagramsDSL"; rootElementSettings.Version = new global::System.Version("1.0.0.0"); // Carry out the normal serialization. rootSerializer.Write(serializationContext, info, writer, rootElementSettings); } char[] chars = encoding.GetChars(newFileContent.GetBuffer()); // search the open angle bracket and trim off the Byte Of Mark. result = new string(chars); int indexPos = result.IndexOf('<'); if (indexPos > 0) { // strip off the leading Byte Of Mark. result = result.Substring(indexPos); } // trim off trailing 0s. result = result.TrimEnd('\0'); return(result); }
static private string ProbeChars(byte[] readBytes, int count) { string result = ""; System.Text.Encoding windows1252Encoding = System.Text.Encoding.GetEncoding(1252); char[] charBuffer = new char[count]; for (int i = 0; i < count; i++) { if (readBytes[i] >= 32 && readBytes[i] < 128) { windows1252Encoding.GetChars(readBytes, i, 1, charBuffer, i); } else { charBuffer[i] = '.'; } result += charBuffer[i]; } return(result); }
public string GenerateToFile() { System.Text.Encoding big5 = HROne.Taxation.TaxationGeneration.GetTaxationFileEncoding(); string exportFileName = exportFileName = System.IO.Path.GetTempFileName(); exportFileName = System.IO.Path.GetTempFileName(); System.IO.StreamWriter writer = new System.IO.StreamWriter(exportFileName, false, big5); //Encoding utf8 = System.Text.Encoding.GetEncoding("utf-8"); string taxFileData = HROne.Taxation.TaxationGeneration.GenerateTaxationFileData(dbConn, taxFormID); //byte[] taxFileByteArray = utf8.GetBytes(taxFileData); //byte[] taxFileByteArrayBig5 = System.Text.Encoding.Convert(utf8, big5, taxFileByteArray); byte[] taxFileByteArrayBig5 = big5.GetBytes(taxFileData); char[] taxFileCharArrayBig5 = big5.GetChars(taxFileByteArrayBig5); writer.Write(taxFileCharArrayBig5); writer.Close(); return(exportFileName); }
public static void Compare(Encoding encoding, Encoding winEncoding, int range) { StringBuilder encodingChars = new StringBuilder(); StringBuilder winChars = new StringBuilder(); char[] encodingCharArray = new char[range]; char[] winCharArray = new char[range]; //decode bytes to characters / string for (int i = 0; i < range; i++) { char encodingChar = encoding.GetChars(new[] {(byte) i}).Single(); char winChar = winEncoding.GetChars(new[] {(byte) i}).Single(); Debug.Assert(encodingChar == winChar, "Got different characters for byte " + i + ": " + encodingChar + " / " + winChar); encodingCharArray[i] = encodingChar; winCharArray[i] = winChar; encodingChars.Append(encodingChar); winChars.Append(winChar); } //encode characters byte[] encodingBytes = encoding.GetBytes(encodingCharArray); byte[] winBytes = encoding.GetBytes(winCharArray); Debug.Assert(encodingBytes.Length == winBytes.Length, "Encoded char arrays return byte arrays of different sizes: " + encodingBytes.Length + " vs. " + winBytes.Length); for (int i = 0; i < encodingBytes.Length; i++) { byte encodingByte = encodingBytes[i]; byte winByte = winBytes[i]; Debug.Assert(encodingByte == winByte, "Got different bytes at index " + i + ": " + encodingByte + " / " + winByte); } Console.Out.WriteLine("Compared encodings successfully for " + range + " bytes."); }
public string ProtocoloBinario() { System.Text.StringBuilder Comando = new System.Text.StringBuilder(); Comando.Append(CaracteresDeControl.PROTO_STX); // STX Start of Frame Comando.Append((char)Secuencia); // SN Sequence Number byte[] Cmd = new byte[1] { (byte)CodigoComando }; Comando.Append(DefaultEncoding.GetChars(Cmd)); // Comando if (Campos != null && Campos.Length > 0) { // Params foreach (string Param in Campos) { Comando.Append(CaracteresDeControl.PROTO_FS); // FS Field Separator Comando.Append(Param); } } Comando.Append(CaracteresDeControl.PROTO_ETX); // ETX End of Frame //Calculo el BCC long BCC = 0; byte[] ComandoBytes = DefaultEncoding.GetBytes(Comando.ToString()); for (int n = 0; n < ComandoBytes.Length; n++) { BCC += ComandoBytes[n]; } Comando.Append(System.Convert.ToString(BCC, 16).ToUpper().PadLeft(4, '0')); return(Comando.ToString()); }
/// <summary> /// Reads a single line from the Stream /// </summary> /// <param name="stream">The stream to read from</param> /// <param name="encoding">The encoding to interpret the text</param> /// <returns>The line read, without the newline character(s)</returns> public static string ReadLine(this Stream stream, Encoding encoding) { byte[] buffer = new byte[8]; // max character bytes int bufferPos = 0; StringBuilder line = new StringBuilder(100); int c; bool lineRead = false; Decoder decoder = encoding.GetDecoder(); while ((c = stream.ReadByte()) != -1) { if (c == '\n') { lineRead = true; // strip any '\r' immediately preceding if ((line.Length > 0) && (line[line.Length - 1] == '\r')) { line.Remove(line.Length - 1, 1); } // and break break; } if (bufferPos >= buffer.Length) throw new InvalidDataException("Invalid character read from stream."); buffer[bufferPos++] = (byte)c; if (decoder.GetCharCount(buffer, 0, bufferPos) != 1) continue; line.Append(encoding.GetChars(buffer, 0, bufferPos)); bufferPos = 0; } if (c == -1 && lineRead == false) throw new IOException("Stream shut down while reading line."); return line.ToString(); }
static char[] GetChars(MemoryStream b, Encoding e) { var buffer = b.GetBufferSegment(); return e.GetChars(buffer.Array, buffer.Offset, buffer.Count); }
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return(encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex)); }
public static byte[] Convert (Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { if (srcEncoding == null) { throw new ArgumentNullException ("srcEncoding"); } if (dstEncoding == null) { throw new ArgumentNullException ("dstEncoding"); } if (bytes == null) { throw new ArgumentNullException ("bytes"); } if (index < 0 || index > bytes.Length) { throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array")); } if (count < 0 || (bytes.Length - index) < count) { throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array")); } return dstEncoding.GetBytes (srcEncoding.GetChars (bytes, index, count)); }
public static String ReadAllText(String path, System.Text.Encoding enc) { return(new String(enc.GetChars(ReadAllBytes(path)))); }
private void GetCharsTestBuffer(Encoding encoding, byte[] inputBuffer, int inputIndex, int inputCount, int outputIndex, int bufferSize, string expectedOutput, int expectedOutputCount) { var buffer = new char[bufferSize]; var result = encoding.GetChars(inputBuffer, inputIndex, inputCount, buffer, outputIndex); var actual = new string(buffer); Assert.Equal(expectedOutputCount, result); Assert.Equal(expectedOutput, actual); }
public static Char[] ToCharArray(Object value, Encoding encoding) { if (value == null) { return null; } if (value is Char[]) { return (Char[])value; } if (value is String) { return ((String)value).ToCharArray(); } if (value is StringBuilder) { return value.ToString().ToCharArray(); } if (value is Byte[]) { return encoding.GetChars((Byte[])value); } if (value is Array) { return (Char[])ToArray((Array)value, typeofCharArray, encoding); } if (value is AssocArray) { return (Char[])ToArray((AssocArray)value, typeofCharArray, encoding); } if (value is ArrayList) { return (Char[])ToArray((ArrayList)value, typeofCharArray, encoding); } if (value is IDictionary) { return (Char[])ToArray((IDictionary)value, typeofCharArray, encoding); } if (value is ICollection) { return (Char[])ToArray((ICollection)value, typeofCharArray, encoding); } return value.ToString().ToCharArray(); }
private static char[] getChars(MemoryStream buffer, Encoding encoding) { return encoding.GetChars (buffer.GetBuffer (), 0, (int) buffer.Length); }
// Converts a range of bytes in a byte array from one encoding to another. // This method converts count bytes from bytes starting at // index index from srcEncoding to dstEncoding, and // returns a new byte array containing the result of the conversion. // public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { if (srcEncoding == null || dstEncoding == null) { throw new ArgumentNullException((srcEncoding == null ? "srcEncoding" : "dstEncoding"), "Array"); } if (bytes == null) { throw new ArgumentNullException("bytes", "Array"); } return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count)); }
public char[] ReadChars(Encoding encoding, int count) { int size; size = GetEncodingSize(encoding); FillBuffer(size * count, size); return encoding.GetChars(buffer, 0, size * count); }
public char ReadChar(Encoding encoding) { int size; size = GetEncodingSize(encoding); FillBuffer(size, size); return encoding.GetChars(buffer, 0, size)[0]; }
private static string encode(byte b1, byte b2) { System.Text.Encoding ecode = System.Text.Encoding.GetEncoding("GB18030"); Byte[] codeBytes = { b1, b2 }; return(ecode.GetChars(codeBytes)[0].ToString()); }
public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { if (srcEncoding == null || dstEncoding == null) { throw new ArgumentNullException((srcEncoding == null ? nameof(srcEncoding) : nameof(dstEncoding)), Environment.GetResourceString("ArgumentNull_Array")); } if (bytes == null) { throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); } Contract.Ensures(Contract.Result<byte[]>() != null); return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count)); }
public unsafe static int GetChars(Encoding encoding, byte* bytes, int byteCount, char* chars, int charCount) { Contract.Assert(encoding != null); if (bytes == null || chars == null) { throw new ArgumentNullException(bytes == null ? "bytes" : "chars", Environment.GetResourceString("ArgumentNull_Array")); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException(charCount < 0 ? "charCount" : "byteCount", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); return encoding.GetChars(bytes, byteCount, chars, charCount, decoder: null); }
private void GetCharsTestAutoBuffer(Encoding encoding, byte[] inputBuffer, int inputIndex, int inputCount, int outputIndex, string expectedOutput, int expectedOutputCount) { var outputBuffer = new char[encoding.GetCharCount(inputBuffer, inputIndex, inputCount)]; var result = encoding.GetChars(inputBuffer, inputIndex, inputCount, outputBuffer, outputIndex == COUNT_AUTO ? 0 : outputIndex); var actual = new string(outputBuffer); Assert.Equal(expectedOutputCount, result); Assert.Equal(expectedOutput, actual); }
public static void Main() { Thread.Sleep(1000); led.Write(false); if (isCharging.Read()) { PWM printerLight = new PWM(Pins.GPIO_PIN_D5); printerLight.SetPulse(100, 0); printerLight.SetDutyCycle(100); while (true) { for (int pulse = 0; pulse < 15; pulse++) { for (uint i = 0; i < 100; i++) { printerLight.SetDutyCycle(i); Thread.Sleep(15); } for (uint i = 0; i < 100; i++) { printerLight.SetDutyCycle(100 - i); Thread.Sleep(10); } Thread.Sleep(2000); } } } try { System.Text.Encoding enc = System.Text.Encoding.UTF8; int fileNum = randy.Next(19999); var fileStream = File.Open(@"SD\rand.txt", FileMode.Open); byte[] randNum = new byte[30]; fileStream.Read(randNum, 0, 30); int seed = int.Parse(new string(enc.GetChars(randNum)).Trim()); randy = new Random(seed); fileStream.Close(); fileStream = File.OpenWrite(@"SD\rand.txt"); byte[] tempToWriteInt = enc.GetBytes((seed + 1).ToString() + " "); fileStream.Write(tempToWriteInt, 0, tempToWriteInt.Length); fileStream.Close(); var stream = File.Open(@"SD\chain\" + fileNum + ".txt", FileMode.Open, FileAccess.Read); byte[] buffer = new byte[1024]; stream.Read(buffer, 0, buffer.Length); stream.Close(); PrintText = new string(enc.GetChars(buffer)); } catch (Exception e) { PrinterTest("Could not access SD Card. Or other issues related to generating text"); } while (true) { iRobotTest(); //there is text to be printed! // todo: stop robot // todo: start lights flashing (probably around the printer) PWM printerLight = new PWM(Pins.GPIO_PIN_D5); printerLight.SetPulse(100, 0); printerLight.SetDutyCycle(100); for (int pulse = 0; pulse < 10; pulse++) { for (uint i = 0; i < 100; i++) { printerLight.SetDutyCycle(i); Thread.Sleep(3); } for (uint i = 0; i < 100; i++) { printerLight.SetDutyCycle(100 - i); Thread.Sleep(3); } } if (PRINT) { Thread.Sleep(1500); PrintPoem(PrintText); } for (int pulse = 0; pulse < 15; pulse++) { for (uint i = 0; i < 100; i++) { printerLight.SetDutyCycle(i); Thread.Sleep(10); } for (uint i = 0; i < 100; i++) { printerLight.SetDutyCycle(100 - i); Thread.Sleep(10); } } printerLight.SetDutyCycle(0); PowerState.RebootDevice(false); } }
public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { if (srcEncoding == null || dstEncoding == null) { throw new ArgumentNullException((srcEncoding == null ? "srcEncoding" : "dstEncoding"), SR.ArgumentNull_Array); } if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } Contract.Ensures(Contract.Result<byte[]>() != null); return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count)); }
/// <summary> /// バイト配列の中から終端が\0で表された文字列を取り出す。 /// </summary> /// <remarks> /// バイト配列の長さはInt32.MaxValueを超えていても良い。 /// </remarks> /// <param name="bytes">デコードする最初のバイトへのポインタ</param> /// <param name="enc">文字エンコーディング</param> /// <returns>文字列(\0は含まない)</returns> public static unsafe string GetString(byte* bytes, Encoding enc) { //バイト長のカウント int byteCount = 0; while (*bytes != Nul) //終端\0に到達するまでシーク { checked { byteCount++; } //文字列のバイト長がInt32.MaxValueを超えたならエラー bytes++; } bytes -= byteCount; //生成されうる最大文字数のバッファを確保 int maxCharCount = enc.GetMaxCharCount(byteCount); fixed (char* buff = new char[maxCharCount]) { //バイト配列を文字列にデコード int len = enc.GetChars(bytes, byteCount, buff, maxCharCount); return new string(buff, 0, len); } }
public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { if ((srcEncoding == null) || (dstEncoding == null)) { throw new ArgumentNullException((srcEncoding == null) ? "srcEncoding" : "dstEncoding", Environment.GetResourceString("ArgumentNull_Array")); } if (bytes == null) { throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); } return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count)); }
public static string UUGetString(this byte[] obj, int index, int size, Encoding encoding) { string result = string.Empty; if (obj != null && obj.Length >= (index + size)) { int endIndex = index + size; int dataLength = obj.Length; int realSize = 0; for (int i = index; i < dataLength && i < endIndex && obj[i] != 0; i++) { ++realSize; } byte[] subData = obj.UUGetBytes(index, realSize); result = new string(encoding.GetChars(subData)); } return result; }
public static T[] ToArray <T>(this ArrayInstance array, int count, System.Text.Encoding encoding, bool exact = false) { Type toType = typeof(T); List <T> t = new List <T>(); int i = 0; for (; i < array.Length && i < count; i++) { object val = array[i]; if (val is String || val is ConcatenatedString) { if (toType == typeof(byte)) { var x = val.ToString(); byte[] tmp = encoding.GetBytes(x); foreach (byte b in tmp) { try { val = Convert.ChangeType(b, typeof(T)); t.Add((T)val); } catch { } } } else if (toType == typeof(char)) { var x = val.ToString(); char[] tmp = encoding.GetChars(encoding.GetBytes(x)); foreach (char c in tmp) { try { val = Convert.ChangeType(c, typeof(T)); t.Add((T)val); } catch { } } } else { t.Add((T)val); } } else if (val is NumberInstance instance) { t.Add((T)(object)instance.Value); } else if (!(val is ObjectInstance)) { try { val = Convert.ChangeType(val, typeof(T)); t.Add((T)val); } catch { } } } if (exact) { while (i < count) { t.Add(default);
/// <summary> /// Reads the variable-length string that is terminated either by zero-char or end of stream. /// After reading, the position will be set after zero-char terminator. /// </summary> /// <param name="encoding">The encoding.</param> /// <returns>String</returns> public string ReadVariableString(Encoding encoding) { // This method reads a block of bytes to "bytes" from stream, then it decodes it into "chars" by using // the decoder of specified "encoding". This ensures correct decoding of single- or multi-byte strings. // Then "chars" are scanned for zero-char (terminator) or end of stream. Non-zero chars are added to the // output "text" list and then returned as string. // If zero-char is found then the stream postion is returned back to first byte after zero-char. // This seems to be better than using some complex zero-char locator method and then calling // Encoding.GetString() method. var text = new List<char>(_SIZE); var bytes = GetBytesBuffer(); var chars = GetCharsBuffer(); var decoder = encoding.GetDecoder(); var encoder = encoding.GetEncoder(); var isTerminated = false; decoder.Reset(); while (!isTerminated) { var byteCount = _stream.Read(bytes, 0, _SIZE); var charCount = encoding.GetChars(bytes, 0, byteCount, chars, 0); for (int i = 0; i < charCount; i++) { var c = chars[i]; if (c == Char.MinValue) { var offset = encoder.GetByteCount(chars, 0, i + 1, true) - byteCount; _stream.Seek(offset, SeekOrigin.Current); isTerminated = true; break; } text.Add(c); } if (!isTerminated && byteCount < _SIZE) { isTerminated = true; } } return new String(text.ToArray()); }
private void GetCharsTestNullBuffer(Encoding encoding, byte[] inputBuffer, int inputIndex, int inputCount, int outputIndex, string expectedOutput, int expectedOutputCount) { var result = encoding.GetChars(inputBuffer, inputIndex, inputCount, null, 0); }
private bool pLoad(ref GCDrawingfield drawing) { drawing_ = drawing; layerNames = new Dictionary <string, string>(); valid = true; resetModal(); try { statusUpdateUI?.Invoke("Loading"); progressUpdateUI?.Invoke(0); Stream s = File.OpenRead(filename); if (filename.ToLower().EndsWith("gz")) { using GZipStream gzs = new(s, CompressionMode.Decompress); MemoryStream ms = new(); gzs.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); br = new EndianBinaryReader(EndianBitConverter.Big, ms); } else { br = new EndianBinaryReader(EndianBitConverter.Big, s); } System.Text.Encoding ascii = System.Text.Encoding.ASCII; cell_ = null; long pos = br.BaseStream.Position; long len = br.BaseStream.Length; long updateInterval = len / 100; double progress = 0; while (pos < len) { switch (pos % updateInterval) { case 0: progressUpdateUI?.Invoke(progress); progress += 0.01f; break; } reclen = br.ReadUInt16(); record = br.ReadByte(); type = br.ReadByte(); switch (type) { case 0: break; // no data case 1: items = (reclen - 4) / 2; // bit array break; case 2: items = (reclen - 4) / 2; // two byte signed int break; case 3: items = (reclen - 4) / 4; // four byte signed int break; case 4: items = (reclen - 4) / 4; // four byte real break; case 5: items = (reclen - 4) / 8; // eight byte real break; case 6: items = reclen - 4; // ASC break; } switch (record) { case 0: // header help16 = br.ReadInt16(); break; case 1: // bgnlib drawing_.modyear = br.ReadInt16(); drawing_.modmonth = br.ReadInt16(); drawing_.modday = br.ReadInt16(); drawing_.modhour = br.ReadInt16(); drawing_.modmin = br.ReadInt16(); drawing_.modsec = br.ReadInt16(); // drawing mod time above drawing_.accyear = br.ReadInt16(); drawing_.accmonth = br.ReadInt16(); drawing_.accday = br.ReadInt16(); drawing_.acchour = br.ReadInt16(); drawing_.accmin = br.ReadInt16(); drawing_.accsec = br.ReadInt16(); // drawing access time above break; case 2: // LIBNAM byte[] tmp_lbnbyte = br.ReadBytes(items); char[] tmplbnchars = new char[ascii.GetCharCount(tmp_lbnbyte, 0, tmp_lbnbyte.Length)]; ascii.GetChars(tmp_lbnbyte, 0, tmp_lbnbyte.Length, tmplbnchars, 0); drawing_.libname = new string(tmplbnchars); // br.ReadString(); // Some files have null termination issues. string[] lNTokens = drawing_.libname.Split(new [] { '\0' }); drawing_.libname = lNTokens[0]; break; case 3: // UNITS double_ = read8ByteReal(); drawing_.userunits = double_; double_ = read8ByteReal(); drawing_.databaseunits = double_; break; case 4: // ENDLIB break; case 5: // BGNSTR cell_ = drawing_.addCell(); cell_.modyear = br.ReadInt16(); cell_.modmonth = br.ReadInt16(); cell_.modday = br.ReadInt16(); cell_.modhour = br.ReadInt16(); cell_.modmin = br.ReadInt16(); cell_.modsec = br.ReadInt16(); cell_.accyear = br.ReadInt16(); cell_.accmonth = br.ReadInt16(); cell_.accday = br.ReadInt16(); cell_.acchour = br.ReadInt16(); cell_.accmin = br.ReadInt16(); cell_.accsec = br.ReadInt16(); break; case 6: // STRNAM byte[] tmp_strnbyte = br.ReadBytes(items); char[] tmpstrnchars = new char[ascii.GetCharCount(tmp_strnbyte, 0, tmp_strnbyte.Length)]; ascii.GetChars(tmp_strnbyte, 0, tmp_strnbyte.Length, tmpstrnchars, 0); cell_.cellName = new string(tmpstrnchars); // Some files have null termination issues. string[] tokens = cell_.cellName.Split(new [] { '\0' }); cell_.cellName = tokens[0]; break; case 7: // ENDSTR break; case 8: // BONDRY -> Polygon modal.elementmode = 110; break; case 9: //PATH modal.elementmode = 150; modal.angle = 0; modal.mag = 1; modal.mirror_x = false; modal.width = 0; modal.cap = 0; modal.endExt = 0; modal.beginExt = 0; break; case 10: //SREF modal.elementmode = 120; modal.angle = 0; modal.mag = 1; modal.mirror_x = false; modal.rotate = false; modal.mag_ = false; break; case 11: //AREF modal.elementmode = 130; modal.angle = 0; modal.mag = 1; modal.mirror_x = false; modal.rotate = false; modal.mag_ = false; break; case 12: //TEXT modal.elementmode = 140; modal.angle = 0; modal.mag = 1; modal.width = 0; modal.mirror_x = false; modal.rotate = false; modal.mag_ = false; modal.presentation = 0; break; case 13: //LAYER modal.layer = br.ReadInt16(); break; case 14: //DATATYPE modal.datatype = br.ReadInt16(); try { layerNames.Add("L" + modal.layer + "D" + modal.datatype, "L" + modal.layer + "D" + modal.datatype); } catch (Exception) { } break; case 15: //WIDTH modal.width = br.ReadInt32(); switch (modal.width) { case < 0: modal.width = -modal.width; break; } modal.width = modal.width switch { // Zero width is problematic for Variance and Quilt. 0 => 10, _ => modal.width }; break; case 16: //XY modal.point_array = new GeoLibPoint[items / 2]; for (int g = 0; g < modal.point_array.Length; g++) { int32x = br.ReadInt32(); int32y = br.ReadInt32(); modal.point_array[g] = new GeoLibPoint(int32x, int32y); } break; case 17: //ENDEL // Looks like some cases, we don't register the associated LD (e.g. layers with only text). Workaround for now until cause is understood. try { layerNames.Add("L" + modal.layer + "D" + modal.datatype, "L" + modal.layer + "D" + modal.datatype); } catch (Exception) { } switch (modal.elementmode) { case 100: addBox(); break; case 110: addPolygon(); break; case 120: addCellRef(); break; case 130: addCellRefArray(); break; case 140: addText(); break; case 150: addPath(); break; } resetModal(); break; case 18: //SNAME byte[] tmp_snamebyte = br.ReadBytes(items); char[] tmpnamechars = new char[ascii.GetCharCount(tmp_snamebyte, 0, tmp_snamebyte.Length)]; ascii.GetChars(tmp_snamebyte, 0, tmp_snamebyte.Length, tmpnamechars, 0); modal.sname = new string(tmpnamechars); // Some files have null termination issues. string[] sNtokens = modal.sname.Split(new [] { '\0' }); modal.sname = sNtokens[0]; break; case 19: //COLROW modal.anzx = br.ReadInt16(); modal.anzy = br.ReadInt16(); break; /*case 20: //TXTNOD * break; * case 21: //NODE * break;*/ case 22: //TXTTYP modal.textType = br.ReadInt16(); modal.datatype = modal.textType; // we don't treat text differently. break; case 23: //PRSTTN modal.presentation = br.ReadInt16() & 0x000F; break; /*case 24: //SPACNG * break;*/ case 25: //STRING byte[] tmp_strbyte = br.ReadBytes(items); char[] tmpstrchars = new char[ascii.GetCharCount(tmp_strbyte, 0, tmp_strbyte.Length)]; ascii.GetChars(tmp_strbyte, 0, tmp_strbyte.Length, tmpstrchars, 0); modal.sname = new string(tmpstrchars); // Some files have null termination issues. string[] sN2tokens = modal.sname.Split(new [] { '\0' }); modal.sname = sN2tokens[0]; break; case 26: //STRANS int16 = br.ReadInt16(); modal.mirror_x = (int16 & 0x8000) != 0; modal.rotate = (int16 & 0x0002) != 0; modal.mag_ = (int16 & 0x0004) != 0; break; case 27: //MAG modal.mag = read8ByteReal(); break; case 28: //ANGLE modal.angle = read8ByteReal(); break; /*case 29: //UINTEG * break; * case 30: //USTRNG * break; * case 31: //REFLIB * s=readString(&ts,items); * if (layout::debug){ * printf("REFLIB %s\n",s.latin1()); * } * break; * case 32: //FONTS * break;*/ case 33: //PTHTYP modal.cap = br.ReadInt16(); break; /*case 34: //GENRTS * break; * case 35: //ATRTBL * break; * case 36: //STPTBL * break; * case 37: //STRTYP * break; * case 38: //EFLAGS * break; * case 39: //ELKEY * break; * case 40: //LNKTYP * break; * case 41: //LNKKEYa * break; * case 42: //NODTYP * break; * case 43: //PROATR * break; * case 44: //PROVAL * break;*/ case 45: //BOX modal.elementmode = 100; break; case 46: //BOXTYP modal.boxType = br.ReadInt16(); break; /*case 47: //PLEX * break;*/ case 48: //BGNEXTN modal.beginExt = br.ReadInt32(); break; case 49: //ENDEXTN modal.endExt = br.ReadInt32(); break; /*case 50: //TAPNUM * break; * case 51: //TAPCOD * break; * case 52: //STRCLS * break; * case 53: //RESRVD * break; * case 54: //FORMAT * break; * case 55: //MASK * break; * case 56: //ENDMSK * break; * case 57: //LDIRSZ * break; * case 58: //SRFNAM * break; * case 59: //LIBSCR * break;*/ default: for (int i = 0; i < items; i++) { switch (type) { case 0: // No Data break; case 1: // Bit Array int16 = br.ReadInt16(); break; case 2: // Two Byte signed int int16 = br.ReadInt16(); break; case 3: // Four Byte signed int int32 = br.ReadInt32(); break; case 4: // Four byte real int32 = br.ReadInt32(); break; case 5: // Eight byte real int32 = br.ReadInt32(); break; case 6: // ASC help = br.ReadByte(); break; } } break; } pos = br.BaseStream.Position; } try { drawing_.active_cell = drawing.findCellIndex(cell_.cellName); drawing_.resize(drawing_.userunits / 1E-3); } catch (Exception) { const string err = "Unable to find any cells. Is this file legal GDS?"; error_msgs.Add(err); throw new Exception(err); } statusUpdateUI?.Invoke("Done"); progressUpdateUI?.Invoke(1.0f); } catch (Exception e) { valid = false; error_msgs.Add(e.Message); } return(valid); }
static char [] GetChars (MemoryStream b, Encoding e) { return e.GetChars (b.GetBuffer (), 0, (int) b.Length); }
public override char[] GetChars(byte[] bytes) { return(enc.GetChars(bytes)); }