public void WriteToStream(Stream outputStream, Encoding encoding) { outputStream.WriteByte((Byte)'P'); // message length = // Int32 self // name of prepared statement + 1 null string terminator + // query string + 1 null string terminator // + Int16 // + Int32 * number of parameters. Int32 messageLength = 4 + encoding.GetByteCount(_prepareName) + 1 + encoding.GetByteCount(_queryString) + 1 + 2 + (_parameterIDs.Length * 4); //Int32 messageLength = 4 + _prepareName.Length + 1 + _queryString.Length + 1 + 2 + (_parameterIDs.Length * 4); PGUtil.WriteInt32(outputStream, messageLength); PGUtil.WriteString(_prepareName, outputStream, encoding); PGUtil.WriteString(_queryString, outputStream, encoding); PGUtil.WriteInt16(outputStream, (Int16)_parameterIDs.Length); for(Int32 i = 0; i < _parameterIDs.Length; i++) PGUtil.WriteInt32(outputStream, _parameterIDs[i]); }
public static byte[] MakeReqSaveMapNameInfoBody(string uID, string dName, string dInfo, short totalRoomNum) { System.Text.Encoding utf8 = System.Text.Encoding.UTF8; var uIDLength = utf8.GetByteCount(uID); var uIDByte = utf8.GetBytes(uID); var dNameLength = utf8.GetByteCount(dName); var dNameByte = utf8.GetBytes(dName); var dInfoLength = utf8.GetByteCount(dInfo); var dInfoByte = utf8.GetBytes(dInfo); var totalRoomNumber = BitConverter.GetBytes((short)totalRoomNum); PacketHeader pHeader = MakePacketHeader(PACKETID.REQ_SAVE_MAP_NAME_INFO, 10 + 10 + 30 + 2); byte[] ret = new byte[PACKET_HEADER_SIZE + 10 + 10 + 30 + 2]; Buffer.BlockCopy(pHeader.pID, 0, ret, 0, 2); Buffer.BlockCopy(pHeader.bodySize, 0, ret, 2, 2); Buffer.BlockCopy(uIDByte, 0, ret, PACKET_HEADER_SIZE, Mathf.Min(10, uIDLength)); Buffer.BlockCopy(dNameByte, 0, ret, PACKET_HEADER_SIZE + 10, Mathf.Min(10, dNameLength)); Buffer.BlockCopy(dInfoByte, 0, ret, PACKET_HEADER_SIZE + 20, Mathf.Min(30, dInfoLength)); Buffer.BlockCopy(totalRoomNumber, 0, ret, PACKET_HEADER_SIZE + 50, 2); return(ret); }
public void WriteToStream(Stream outputStream, Encoding encoding) { NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "WriteToStream"); switch (protocolVersion) { case ProtocolVersion.Version2 : // Write the size of the packet. // 4 + (passwordlength + 1) -> Int32 + NULL terminated string. // output_stream.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(4 + (password.Length + 1))), 0, 4); PGUtil.WriteInt32(outputStream, 4 + encoding.GetByteCount(password) + 1); // Write String. PGUtil.WriteString(password, outputStream, encoding); break; case ProtocolVersion.Version3 : outputStream.WriteByte((Byte)'p'); PGUtil.WriteInt32(outputStream, 4 + encoding.GetByteCount(password) + 1); // Write String. PGUtil.WriteString(password, outputStream, encoding); break; } }
public override int GetByteLength(Encoding encoding) { int byteLength = 0; byteLength += encoding.GetByteCount(indicator); foreach (SubField sf in subfields) { byteLength += encoding.GetByteCount(Field.SubFieldStart.ToString()); byteLength += sf.GetByteLength(encoding); } byteLength += encoding.GetByteCount(Field.FieldEnd.ToString()); return byteLength; }
public StringStream(string str, Encoding encoding = null) { _string = str ?? string.Empty; _encoding = encoding ?? Encoding.UTF8; _byteLength = _encoding.GetByteCount(_string); }
internal static string ReadStringInternalDynamic(this Stream stream, Encoding encoding, char end) { int characterSize = encoding.GetByteCount("e"); Debug.Assert(characterSize == 1 || characterSize == 2 || characterSize == 4); string characterEnd = end.ToString(); int i = 0; byte[] data = new byte[128 * characterSize]; while (true) { if (i + characterSize > data.Length) { Array.Resize(ref data, data.Length + (128 * characterSize)); } int read = stream.Read(data, i, characterSize); Debug.Assert(read == characterSize); if (encoding.GetString(data, i, characterSize) == characterEnd) { break; } i += characterSize; } if (i == 0) { return ""; } return encoding.GetString(data, 0, i); }
public static string PadRightInBytes ( this string text , int totalWidth , char paddingChar = ' ' , Encoding encoding = null ) { if (encoding == null) { encoding = Encoding.GetEncoding("gb2312"); } totalWidth -= ( encoding.GetByteCount(text) - text.Length ); return text .PadRight ( totalWidth , paddingChar ); }
public void GetByteCount() { System.Text.Encoding enc = GetEncoding(); var byteCount = enc.GetByteCount("abc"); Assert.Equal <int>(5, byteCount); }
static void DoEncoding() { //通过基类Encoding的单例属性获得具体encoding System.Text.Encoding utf8encoding = System.Text.Encoding.UTF8; //也可以直接创建该具体encoding, 但每次创建都要new System.Text.UnicodeEncoding alternative = new UnicodeEncoding(false, false);//这时可以指定特定encoding的参数, 如utf16的高低序 string s = "Aureliano Jose"; byte[] encode = utf8encoding.GetBytes(s); //这个方法把byte array中每个0000 0000以十六进制的数字显示出来 Console.WriteLine(BitConverter.ToString(encode) + " Count:" + utf8encoding.GetByteCount(s)); string decode = utf8encoding.GetString(encode); Console.WriteLine(decode); //用正确的code page指定一个不常用的编码格式 Encoding e = System.Text.Encoding.GetEncoding("Shift-JIS"); decode = e.GetString(encode); Console.WriteLine(decode); //如果用了错误的编码方式就得不到原结果, 这就是文本乱码的来历 System.Text.Encoding utf16encoding = System.Text.Encoding.Unicode; string decode16 = utf16encoding.GetString(encode); Console.WriteLine(decode16); }
/// <summary> /// 字符串截取 /// 2009-3-5 by Shaipe /// </summary> /// <param name="content">The content.</param> /// <param name="length">The length.</param> /// <returns>System.String</returns> public static string SubString(string content, int length) { System.Text.StringBuilder sb = null; try { sb = new System.Text.StringBuilder(); System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("gb2312"); int totalLength = 0; foreach (char contentChar in content) { int size = encoding.GetByteCount(new char[] { contentChar }); //获得1或2,中文2,英文1 if (totalLength + size > length - 2) { sb.Append("..."); break; } sb.Append(contentChar); totalLength += size; } } catch { sb.Append(""); } return(sb.ToString()); }
public unsafe static int GetByteCount(Encoding encoding, char[] chars, int index, int count) { // Validate parameters Contract.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here if (chars == null) { throw new ArgumentNullException("chars", Environment.GetResourceString("ArgumentNull_Array")); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException(index < 0 ? "index" : "count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); } Contract.EndContractBlock(); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the (internal) pointer version fixed (char* pChars = chars) return encoding.GetByteCount(pChars + index, count, encoder: null); }
public void WriteToStream( Stream outputStream, Encoding encoding ) { //NpgsqlEventLog.LogMsg( this.ToString() + _commandText, LogLevel.Debug ); String commandText = _command.GetCommandText(); // Tell to mediator what command is being sent. _command.Connector.Mediator.SqlSent = commandText; // Send the query to server. // Write the byte 'Q' to identify a query message. outputStream.WriteByte((Byte)'Q'); if (_protocolVersion == ProtocolVersion.Version3) { // Write message length. Int32 + string length + null terminator. PGUtil.WriteInt32(outputStream, 4 + encoding.GetByteCount(commandText) + 1); } // Write the query. In this case it is the CommandText text. // It is a string terminated by a C NULL character. PGUtil.WriteString(commandText, outputStream, encoding); }
private byte[] GetBytes(string s) { System.Text.Encoding encoding = System.Text.Encoding.UTF8; byte[] bytes = new byte[encoding.GetByteCount(s)]; encoding.GetBytes(s, 0, s.Length, bytes, 0); return(bytes); }
internal static byte[] GetBytes(string self) { System.Text.Encoding encoding = System.Text.Encoding.UTF8; byte[] sbytes = new byte[encoding.GetByteCount(self)]; encoding.GetBytes(self, 0, self.Length, (byte[])(object)sbytes, 0); return(sbytes);//GetSBytesForEncoding(System.Text.Encoding.UTF8, self); }
public MetaData(Roles role, Actions action, ContentTypes contentType, Encoding encoding, string message) { this.role = role; this.action = action; this.contentType = contentType; this.encoding = encoding; messageSize = encoding.GetByteCount(message); }
/// <summary> /// Reads the string data. /// </summary> /// <param name="binaryReader">The binary reader.</param> /// <param name="encoding">The encoding.</param> /// <returns></returns> public static string ReadStringData(this BinaryReader binaryReader, Encoding encoding) { int size = binaryReader.ReadUInt16(); return encoding.GetString( binaryReader.ReadBytes( size * encoding.GetByteCount(" "))); }
public override void Encode(ProtocolBuffer protocolBuffer, object data) { base.Encode(protocolBuffer, data); string s = (string)data; int byteCount = Encoding.GetByteCount(s); LengthCodecHelper.EncodeLength(protocolBuffer.Data.Stream, byteCount); protocolBuffer.Writer.Write(Encoding.GetBytes(s), 0, byteCount); }
public void WriteTextString(ReadOnlySpan <char> value) { int length = s_utf8Encoding.GetByteCount(value); WriteUnsignedInteger(CborMajorType.TextString, (ulong)length); EnsureWriteCapacity(length); s_utf8Encoding.GetBytes(value, _buffer.AsSpan(_offset)); _offset += length; }
public static void WriteNullTermString(this Stream stream, string value, Encoding encoding) { var dataLength = encoding.GetByteCount(value); var data = new byte[dataLength + 1]; encoding.GetBytes(value, 0, value.Length, data, 0); data[dataLength] = 0x00; // '\0' stream.Write(data, 0, data.Length); }
public override void Write(char value) { base.Write(value); RollingLogStreamWriter.TallyKeepingFileStreamWriter byteCount = this; long num = byteCount.tally; System.Text.Encoding encoding = this.Encoding; char[] chrArray = new char[] { value }; byteCount.tally = num + (long)encoding.GetByteCount(chrArray); }
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()); }
public static string StrSubStringForChar(string value, int startindex, int length) { string ret = ""; int start = 0; System.Text.Encoding sjis = System.Text.Encoding.GetEncoding("Shift-JIS"); if (startindex < 0) { startindex = 0; } if (length < 0) { length = 0; } if (startindex == 0) { start = 0; } else { int bytecnt = 0; for (int i = 0; i < value.Length; i++) { bytecnt += sjis.GetByteCount(value.Substring(i, 1)); if (bytecnt >= startindex) { start = i + 1; break; } } } for (int i = 0; i < value.Length; i++) { if (i >= start) { if ((sjis.GetByteCount(ret + value.Substring(i, 1)) <= length) || (length == 0)) { ret += value.Substring(i, 1); } } } return(ret); }
/// <summary> /// Gets the number of bytes for specified string in given encoding. /// </summary> /// <param name="encoding">The encoding.</param> /// <param name="value">The value.</param> /// <returns></returns> public static int GetByteCount(Encoding encoding, string value) { if (encoding == null) { throw new ArgumentNullException("encoding"); } if (value == null) { throw new ArgumentNullException("value"); } return encoding.GetByteCount(value); }
public static IntPtr StringToPtr(string value, Encoding encoding) { var encoder = encoding.GetEncoder(); var length = encoding.GetByteCount(value); // The encoded value is null terminated that's the reason for the '+1'. var encodedValue = new byte[length + 1]; encoding.GetBytes(value, 0, value.Length, encodedValue, 0); var handle = Marshal.AllocHGlobal(new IntPtr(encodedValue.Length)); Marshal.Copy(encodedValue, 0, handle, encodedValue.Length); return handle; }
//Перекодирует 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); }
public static unsafe IntPtr Create(string text, Encoding encoding) { // Avoid unnecessary allocations by allocating the native buffer directly in managed code var byteCount = encoding.GetByteCount(text); var bytesPointer = (byte*)Marshal.AllocHGlobal(byteCount); fixed (char* charsPointer = text) encoding.GetBytes(charsPointer, text.Length, bytesPointer, byteCount); return SafeNativeMethods.objc_msgSend(Class, Selectors.DataWithBytesNoCopyLengthFreeWhenDone, (IntPtr)bytesPointer, checked((IntPtr)byteCount), true); }
/// <summary> /// バイト長を指定して文字列の先頭を切り出す /// </summary> /// <param name="value">対象となる文字列</param> /// <param name="encode">文字コードを指定する /// ShiftJISを明示的に指定したい場合は Encoding.GetEncoding(932) /// </param> /// <param name="size">バイト長</param> /// <returns></returns> public static bool GetStringByteErrMessage(string value, System.Text.Encoding encoding, int size) { if (encoding.GetByteCount(value) <= size) { // 指定サイズ以下の場合そのまま返す return(true); } else { return(false); } }
public void WriteToStream(Stream outputStream, Encoding encoding) { outputStream.WriteByte((Byte)'E'); PGUtil.WriteInt32(outputStream, 4 + encoding.GetByteCount(_portalName) + 1 + 4); PGUtil.WriteString(_portalName, outputStream, encoding); PGUtil.WriteInt32(outputStream, _maxRows); }
/// <summary> /// Runs clang-format on the current selection /// </summary> private void FormatSelection(OptionPageGrid options) { IWpfTextView view = Vsix.GetCurrentView(); if (view == null) { // We're not in a text view. return; } string text = view.TextBuffer.CurrentSnapshot.GetText(); int start = view.Selection.Start.Position.GetContainingLine().Start.Position; int end = view.Selection.End.Position.GetContainingLine().End.Position; if (start >= end) { return; } // convert the utf16 index to multi bytes index start = enc.GetByteCount(text.ToCharArray(), 0, start); end = enc.GetByteCount(text.ToCharArray(), 0, end); int length = end - start; if (length <= 0) { return; } // clang-format doesn't support formatting a range that starts at the end // of the file. if (start >= text.Length && text.Length > 0) { start = text.Length - 1; } string path = Vsix.GetDocumentParent(view); string filePath = Vsix.GetDocumentPath(view); byte[] buffer = enc.GetBytes(text); RunClangFormatAndApplyReplacements(buffer, start, length, path, filePath, options, view); }
public static string ReadASCIIZ(this BinaryReader reader, Encoding encoding) { List<byte> bytes = new List<byte>(); byte[] read; int bytecount = encoding.GetByteCount(" "); while ( (read = reader.ReadBytes(bytecount)).First() != 0 ) { bytes.AddRange(read); } return encoding.GetString(bytes.ToArray()); }
public void WriteToStream(Stream outputStream, Encoding encoding) { outputStream.WriteByte((Byte)'D'); PGUtil.WriteInt32(outputStream, 4 + 1 + encoding.GetByteCount(_portalName) + 1); outputStream.WriteByte((Byte)_whatToDescribe); PGUtil.WriteString(_portalName, outputStream, encoding); }
public static int GetStringLength(string str) { System.Text.Encoding encoding = System.Text.Encoding.Default; try { encoding = System.Text.Encoding.GetEncoding(""); } catch { } return(encoding.GetByteCount(str)); }
public static String convert(string sourceValue, Encoding source, Encoding target) { Encoder encoder = source.GetEncoder(); Decoder decoder = target.GetDecoder(); byte[] cpBytes = source.GetBytes(sourceValue); int bytesCount = source.GetByteCount(sourceValue); byte[] utfBytes = Encoding.Convert(source, target, cpBytes); char[] utfChars = new char[bytesCount]; decoder.GetChars(utfBytes, 0, utfBytes.Length, utfChars, 0); return new String(utfChars); }
public static uint CalcLength(string name, Encoding enc) { int nameBytes; if (name.Length == 1 && name[0] <= 1) { nameBytes = 1; } else { nameBytes = enc.GetByteCount(name); } return (uint)(33 + nameBytes + (((nameBytes & 0x1) == 0) ? 1 : 0)); }
private void InsertUsingEncoding(Encoding encoding, HexBox _hexbox, bool Multiline) { PromptBox prompt = new PromptBox(Multiline); if (prompt.ShowDialog() == DialogResult.OK) { byte[] bytes = new byte[prompt.Value.Length * encoding.GetByteCount("A")]; encoding.GetBytes(prompt.Value, 0, prompt.Value.Length, bytes, 0); _hexbox.ByteProvider.DeleteBytes(_hexbox.SelectionStart, _hexbox.SelectionLength); _hexbox.ByteProvider.InsertBytes(_hexbox.SelectionStart, bytes); _hexbox.Select(_hexbox.SelectionStart, bytes.Length); } }
static public int GetByteCount__String(IntPtr l) { try { System.Text.Encoding self = (System.Text.Encoding)checkSelf(l); System.String a1; checkType(l, 2, out a1); var ret = self.GetByteCount(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
/// <summary> /// Computes the number of bytes required to encode the specified string. /// </summary> /// <remarks> /// Use this Method to calculate the exact number of bytes that <paramref name="s" /> /// will have when beeing encoded. /// <b>Note:</b> No error checking is performed. Make sure <paramref name="s" /> and /// <paramref name="e" /> are not null. /// </remarks> /// <param name="s">The <see cref="String" /> to be encoded.</param> /// <param name="e">The <see cref="Encoding" /> with which the string will be encoded.</param> /// <param name="terminateString"> /// When <b>true</b> one or two zero bytes depending on the Encoding will be appended; else /// nothing wil be appended. /// </param> /// <returns>The number of bytes required to encode <paramref name="s" />.</returns> internal static int ByteCount(string s, Encoding e, bool terminateString) { int count = 0; if (terminateString) { if (e == utf16LE || e == utf16BE) { count = 2; } else { count = 1; } } count += e.GetByteCount(s) + e.GetPreamble().Length; return count; }
////public static int ReadFrom(byte[] src, int offset, bool byteSwap, Encoding enc, out PathTableRecord record) ////{ //// byte directoryIdentifierLength = src[offset + 0]; //// record.ExtendedAttributeRecordLength = src[offset + 1]; //// record.LocationOfExtent = Utilities.ToUInt32LittleEndian(src, offset + 2); //// record.ParentDirectoryNumber = Utilities.ToUInt16LittleEndian(src, offset + 6); //// record.DirectoryIdentifier = IsoUtilities.ReadChars(src, offset + 8, directoryIdentifierLength, enc); //// //// if (byteSwap) //// { //// record.LocationOfExtent = Utilities.BitSwap(record.LocationOfExtent); //// record.ParentDirectoryNumber = Utilities.BitSwap(record.ParentDirectoryNumber); //// } //// //// return directoryIdentifierLength + 8 + (((directoryIdentifierLength & 1) == 1) ? 1 : 0); ////} internal int Write(bool byteSwap, Encoding enc, byte[] buffer, int offset) { int nameBytes = enc.GetByteCount(DirectoryIdentifier); buffer[offset + 0] = (byte)nameBytes; buffer[offset + 1] = 0; // ExtendedAttributeRecordLength; IsoUtilities.ToBytesFromUInt32(buffer, offset + 2, byteSwap ? Utilities.BitSwap(LocationOfExtent) : LocationOfExtent); IsoUtilities.ToBytesFromUInt16(buffer, offset + 6, byteSwap ? Utilities.BitSwap(ParentDirectoryNumber) : ParentDirectoryNumber); IsoUtilities.WriteString(buffer, offset + 8, nameBytes, false, DirectoryIdentifier, enc); if ((nameBytes & 1) == 1) { buffer[offset + 8 + nameBytes] = 0; } return (int)(8 + nameBytes + (((nameBytes & 0x1) == 1) ? 1 : 0)); }
private static String Act2S(string x, int c) { System.Text.Encoding encodeUTF8 = System.Text.Encoding.UTF8; int utf7_cnt = encodeUTF8.GetByteCount(x); int tempint = x.Length * 2 - (x.Length * 3 - utf7_cnt) / 2; String pattern = "[ a-zA-Z]+"; System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(pattern); int _c = rgx.Matches(x).Count; c = tempint > 57 ? (c + 57 * 2 - 3) : c; for (int i = tempint; i < (c - _c); i++) { x += " "; } return(x); }
/// <summary> /// 文字列のハッシュ値を生成する。 /// </summary> /// <param name="word">文字列</param> public WordHash(string word) { sjis = Encoding.GetEncoding("shift_jis"); val1 = 0; val2 = 0; foreach (var ch in word) { if (sjis.GetByteCount(new char[] { ch }) == 1) { val1 |= (ulong)1 << (int)ch % 64 - 1; } else { val2 |= (ulong)1 << (int)ch % 64 - 1; } } }
public static byte[] String2Bytes(String val, Encoding enc = null) { // ReSharper disable RedundantCast if (enc == null) { enc = Encoding.ASCII; } if (string.IsNullOrEmpty(val)) { return BitConverter.GetBytes(IPAddress.HostToNetworkOrder((Int32) 0)); } int cnt = enc.GetByteCount(val); var result = new byte[cnt + sizeof (Int32)]; Array.Copy(enc.GetBytes(val), 0, result, sizeof (Int32), cnt); Array.Copy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder((Int32) cnt)), 0, result, 0, sizeof (Int32)); return result; // ReSharper restore RedundantCast }
/// <summary> /// Initializes a String from a .NET String and /// the desired byte encoding. /// </summary> /// <param name="str">The string.</param> /// <param name="encoding">The desired encoding.</param> public LString( string str, Encoding encoding ) { if( str == null ) { InternalData = null; return; } if( encoding == null ) throw new ArgumentNullException( "encoding" ); var len = encoding.GetByteCount( str ); InternalData = new byte[4 + len]; encoding.GetBytes( str, 0, str.Length, InternalData, 4 ); UpdateHashCode(); }
static public int GetByteCount__A_Char__Int32__Int32(IntPtr l) { try { System.Text.Encoding self = (System.Text.Encoding)checkSelf(l); System.Char[] a1; checkArray(l, 2, out a1); System.Int32 a2; checkType(l, 3, out a2); System.Int32 a3; checkType(l, 4, out a3); var ret = self.GetByteCount(a1, a2, a3); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
public void WriteTextString(ReadOnlySpan <char> value) { int length; try { length = s_utf8Encoding.GetByteCount(value); } catch (EncoderFallbackException e) { throw new ArgumentException("Provided text string is not valid UTF8.", e); } WriteUnsignedInteger(CborMajorType.TextString, (ulong)length); EnsureWriteCapacity(length); s_utf8Encoding.GetBytes(value, _buffer.AsSpan(_offset)); _offset += length; AdvanceDataItemCounters(); }
/// <summary> /// Reads a string null terminated. /// </summary> /// <param name="binaryReader">The binary reader.</param> /// <param name="encoding">The encoding.</param> /// <returns></returns> public static string ReadStringNullTerminated(this BinaryReader binaryReader, Encoding encoding) { var bytes = new List<byte>(); var byteCount = encoding.GetByteCount(" "); while (true) { var currentByte = binaryReader.ReadBytes(byteCount); if (currentByte.First() == 0) { break; } bytes.AddRange(currentByte); } return encoding.GetString(bytes.ToArray()); }
//실제로 파일을 저장한다. private void saveFile(String strPath) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(strPath); System.IO.FileStream fileTxt; //기본 인코딩 타입 얻기 System.Text.Encoding enc = System.Text.Encoding.Default; //기존 파일 삭제 if (fileInfo != null) { fileInfo.Delete(); } //파일 저장 fileTxt = System.IO.File.Open(strPath, System.IO.FileMode.OpenOrCreate); fileTxt.Write(enc.GetBytes(txtMain.Text), 0, enc.GetByteCount(txtMain.Text)); fileTxt.Close(); }
public static string ReadASCIIZF(this BinaryReader reader, Encoding encoding, int length, out byte[] padding) { byte[] bytes = reader.ReadBytes(length); int bytecount = encoding.GetByteCount(" "); byte[] nullsequence = new byte[bytecount]; int split = bytes.IndexOf(nullsequence); if (split <= 0) { padding = bytes.ToArray(); return string.Empty; } else { byte[] stringdata = bytes.Take(split -1 + bytecount).ToArray(); List<byte> temp = bytes.ToList(); temp.RemoveRange(0, split - 1 + bytecount); padding = temp.ToArray(); return encoding.GetString(stringdata); } }
public byte[] WriteToScreen(uint deviceAddress, string text) { if (text.Length > 40) { text = text.Remove(40, text.Length - 40); } System.Text.Encoding encoding = System.Text.Encoding.ASCII; byte[] m_bytes = new byte[encoding.GetByteCount(text) * 7]; int i = 0; byte m_scrPosition; byte m_ASCIIchr; foreach (char ch in text) { m_scrPosition = Convert.ToByte(i / 7); m_ASCIIchr = Convert.ToByte(ch); Array.Copy(Message.GetMessage(deviceAddress, 0x00, 0x15, m_scrPosition, m_ASCIIchr), 0, m_bytes, i, 7); i = i + 7; } return(m_bytes); }
public static string ReadNullTermString( this BinaryReader reader, Encoding encoding ) { int characterSize = encoding.GetByteCount( "e" ); using ( MemoryStream ms = new MemoryStream() ) { while ( true ) { byte[] data = new byte[ characterSize ]; reader.Read( data, 0, characterSize ); if ( encoding.GetString( data, 0, characterSize ) == "\0" ) { break; } ms.Write( data, 0, data.Length ); } return encoding.GetString( ms.ToArray() ); } }
public static string crs2s(string x, int c) { /* * foreach (EncodingInfo ei in Encoding.GetEncodings()) * { * Encoding e = ei.GetEncoding(); * * Console.Write("{0,-15}", ei.CodePage); * if (ei.CodePage == e.CodePage) * Console.Write(" "); * else * Console.Write("*** "); * * Console.Write("{0,-25}", ei.Name); * if (ei.CodePage == e.CodePage) * Console.Write(" "); * else * Console.Write("*** "); * * Console.Write("{0,-25}", ei.DisplayName); * if (ei.CodePage == e.CodePage) * Console.Write(" "); * else * Console.Write("*** "); * Console.Write("{0}_{1}_{2}",x,x.Length,e.GetByteCount(x)); * }*/ System.Text.Encoding encodeUTF8 = System.Text.Encoding.UTF8; int utf7_cnt = encodeUTF8.GetByteCount(x); int tempint = x.Length * 2 - (x.Length * 3 - utf7_cnt) / 2; for (int i = tempint; i < c; i++) { x += " "; } return(x); }
public static string LeftB(string stTarget, int iByteSize, string space) { System.Text.Encoding sjis = System.Text.Encoding.GetEncoding("gb2312"); int TempLen = sjis.GetByteCount(stTarget); if (((iByteSize < 1) || (stTarget.Length < 1))) { return(""); } if ((TempLen <= iByteSize)) { return(stTarget); } byte[] tempByt = sjis.GetBytes(stTarget); string strTemp = sjis.GetString(tempByt, 0, iByteSize); if (strTemp.EndsWith("・")) { strTemp = sjis.GetString(tempByt, 0, (iByteSize - 1)) + space; } return(strTemp); }
public override int GetByteCount(char[] chars) { return(enc.GetByteCount(chars)); }
private static sbyte[] GetSBytesForEncoding(System.Text.Encoding encoding, string s) { sbyte[] sbytes = new sbyte[encoding.GetByteCount(s)]; encoding.GetBytes(s, 0, s.Length, (byte[])(object)sbytes, 0); return(sbytes); }
public static bool IsWideEastAsianWidth_SJIS(this char c) { int byteCount = sjis.GetByteCount(c.ToString()); return(byteCount == 2); }
private int CalculateSize(BsonToken t) { switch (t.Type) { case BsonType.Number: return(8); case BsonType.String: { BsonString str = (BsonString)t; string s = (string)str.Value; str.ByteCount = (s != null) ? Encoding.GetByteCount(s) : 0; str.CalculatedSize = this.CalculateSizeWithLength(str.ByteCount, str.IncludeLength); return(str.CalculatedSize); } case BsonType.Object: { BsonObject obj2 = (BsonObject)t; int num = 4; foreach (BsonProperty property in obj2) { int num2 = 1; num2 += this.CalculateSize(property.Name); num2 += this.CalculateSize(property.Value); num += num2; } num++; obj2.CalculatedSize = num; return(num); } case BsonType.Array: { BsonArray array = (BsonArray)t; int num3 = 4; ulong i = 0L; foreach (BsonToken token in array) { num3++; num3 += this.CalculateSize(MathUtils.IntLength(i)); num3 += this.CalculateSize(token); i += (ulong)1L; } num3++; array.CalculatedSize = num3; return(array.CalculatedSize); } case BsonType.Binary: { BsonBinary binary1 = (BsonBinary)t; byte[] buffer = (byte[])binary1.Value; binary1.CalculatedSize = 5 + buffer.Length; return(binary1.CalculatedSize); } case BsonType.Undefined: case BsonType.Null: return(0); case BsonType.Oid: return(12); case BsonType.Boolean: return(1); case BsonType.Date: return(8); case BsonType.Regex: { BsonRegex regex = (BsonRegex)t; int num5 = 0; num5 += this.CalculateSize(regex.Pattern); num5 += this.CalculateSize(regex.Options); regex.CalculatedSize = num5; return(regex.CalculatedSize); } case BsonType.Integer: return(4); case BsonType.Long: return(8); } throw new ArgumentOutOfRangeException("t", "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type)); }
public override int GetByteCount(char[] chars, int index, int count) { return(_encoding.GetByteCount(chars, index, count)); }
public static int GetStrLen(string strData) { System.Text.Encoding encoder5 = System.Text.Encoding.GetEncoding("GB2312"); return(encoder5.GetByteCount(strData)); }
public static XmlDocument TimbrarDTE(XmlDocument Datos, XmlDocument AutorizacionSII, int flag) { XmlDocument res = new XmlDocument(); res.PreserveWhitespace = true; // 1 obtener la clave para la firma -- 1b cargar /AUTORIZACION/RSASK // Build an RSAParameters structure from the byte array // antes de calcular los parámetros, pasar el módulo que debería ser igual a la clave pública // Create a new RSACSP object, attached to a random, transient key container // 3a obtener el contexto de encripción XmlElement rsask = (XmlElement)AutorizacionSII.SelectSingleNode("/AUTORIZACION/RSASK"); if (null == rsask) { throw new Exception("La firma autorizadora no se encuentra en el documento.\nAsegúrese que se trata del documento entregado por SII."); } byte[] inputBytes = PEMaBytes(rsask.InnerText); XmlElement elModulus = (XmlElement)AutorizacionSII.SelectSingleNode("/AUTORIZACION/CAF/DA/RSAPK/M"); if (null == elModulus) { throw new ArgumentException("No se encuentra la clave pública.", "AutorizaciónSII"); } byte[] modulus = Convert.FromBase64String(elModulus.InnerText); RSAParameters rsa = ParsePEMPrivateKey(inputBytes, modulus, flag); RSACryptoServiceProvider.UseMachineKeyStore = true; RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider(); // Import the parameters into the key container // 3b poner la clave en el hash rsaCSP.ImportParameters(rsa); // 3 crear la firma System.Text.Encoding e1 = System.Text.Encoding.GetEncoding("ISO-8859-1"); string datosAfirmar = Datos.OuterXml; // los datos a firmar, como string int nLength = e1.GetByteCount(datosAfirmar); // preparar un arreglo de bytes para tener los datos byte[] bytesAfirmar = new byte[nLength]; e1.GetBytes(datosAfirmar, 0, datosAfirmar.Length, bytesAfirmar, 0); // obtener los datos como bytes // Obtener el hash SHA1 SHA1 shalgo = new SHA1Managed(); // Encrypt (second arg false says use PKCS#1 padding, not OAEP) byte[] firma = rsaCSP.SignData(bytesAfirmar, shalgo); // Encrypt(hashAcifrar, false); // firmar con RSA // 4 crear el documento de salida XmlElement elTED = res.CreateElement("TED"); elTED.SetAttribute("version", "1.0"); // 5 pegar los datos elTED.InnerXml = Datos.DocumentElement.OuterXml; // 6 pegar la firma XmlElement elFRMT = res.CreateElement("FRMT"); elFRMT.SetAttribute("algoritmo", "SHA1withRSA"); elFRMT.InnerText = Convert.ToBase64String(firma); elTED.AppendChild(elFRMT); res.AppendChild(elTED); rsaCSP.Clear();//cambio MAXIMISE -> libera la llave del store return(res); }
private int GetStrLen(string strData) { System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("GB2312"); return(encoding.GetByteCount(strData)); }
public virtual int GetByteCount(char[] chars, int index, int count) { CheckParams(chars, index, count); return(encoding.GetByteCount(chars, index, count)); }