CSharp · Console
using System;
using System.Text;
public class Program
{
public static void Main()
{
var s1_UTF_16 = "ABC网络D";
var b1_UTF_16 = Encoding.Unicode.GetBytes(s1_UTF_16);
var buffer_UTF_16_default = new byte[b1_UTF_16.Length];
var buffer_UTF_16_ASCII = new byte[b1_UTF_16.Length];
var buffer_UTF_16_UTF8 = new byte[b1_UTF_16.Length];
var buffer_UTF_16 = new byte[b1_UTF_16.Length];
GetAsciiBytes(s1_UTF_16, 0, buffer_UTF_16_default, 0, buffer_UTF_16_default.Length, null);
GetAsciiBytes(s1_UTF_16, 0, buffer_UTF_16_ASCII, 0, buffer_UTF_16_ASCII.Length, Encoding.ASCII);
GetAsciiBytes(s1_UTF_16, 0, buffer_UTF_16_UTF8, 0, buffer_UTF_16_UTF8.Length, Encoding.UTF8);
GetAsciiBytes(s1_UTF_16, 0, buffer_UTF_16, 0, buffer_UTF_16.Length, Encoding.Unicode);
var defaultBufferedString = Encoding.ASCII.GetString(buffer_UTF_16_default);
var asciiBufferedString = Encoding.ASCII.GetString(buffer_UTF_16_ASCII);
var utf8BufferedString = Encoding.UTF8.GetString(buffer_UTF_16_UTF8);
var utf16BufferedString = Encoding.Unicode.GetString(buffer_UTF_16);
WriteToConsole(nameof(defaultBufferedString), defaultBufferedString);
WriteToConsole(nameof(asciiBufferedString), asciiBufferedString);
WriteToConsole(nameof(utf8BufferedString), utf8BufferedString);
WriteToConsole(nameof(utf16BufferedString), utf16BufferedString);
var b_asciiConvertResult = Encoding.Convert(Encoding.Unicode, Encoding.ASCII, b1_UTF_16);
var s_asciiConvertResult = Encoding.ASCII.GetString(b_asciiConvertResult);
WriteToConsole(nameof(s_asciiConvertResult), s_asciiConvertResult);
void WriteToConsole<T>(string nameOf, T value) => Console.WriteLine($"{nameOf} => \"{value}\"");
}
public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length, Encoding encoding)
{
if (toAdd == null)
{
throw new ArgumentNullException(nameof(toAdd));
}
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
int i;
if (encoding == null)
{
for (i = 0; i < length && nameOffset + i < toAdd.Length; ++i)
{
buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i];
}
}
else
{
// It can be more sufficient if using unsafe code or Span(ToCharArray can be omitted)
var chars = toAdd.ToCharArray();
// It can be more sufficient if using Span(or unsafe?) and ArrayPool for temporary buffer
var bytes = encoding.GetBytes(chars, nameOffset, Math.Min(toAdd.Length - nameOffset, length));
i = Math.Min(bytes.Length, length);
Array.Copy(bytes, 0, buffer, bufferOffset, i);
}
// If length is beyond the toAdd string length (which is OK by the prev loop condition), eg if a field has fixed length and the string is shorter, make sure all of the extra chars are written as NULLs, so that the reader func would ignore them and get back the original string
for (; i < length; ++i)
buffer[bufferOffset + i] = 0;
return bufferOffset + length;
}
}