MELSEC PLCで文字列を取得するため。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BytesToShiftJisCharacters
{
/// <summary>
/// バイト配列からSHIFT-JISに変換する
/// </summary>
class Program
{
static void Main(string[] args)
{
// ABC(NULL)
// Little Endian.
var bytes = new byte[][]
{
new byte[] {0x42, 0x41 },
new byte[] {0x00, 0x43 }
};
var convertedBytes = bytes.SelectMany(b => b.Reverse()).ToArray();
Console.WriteLine($"INPUT: {BitConverter.ToString(convertedBytes)}");
// SHIFT-JIS
var shiftJisCharacters = Encoding.GetEncoding("shift-jis").GetString(convertedBytes);
Console.WriteLine($"OUTPUT: {shiftJisCharacters}");
// Short version.
var shorts = new ushort[]
{
BitConverter.ToUInt16(new byte[] { 0x42, 0x41 }, 0),
BitConverter.ToUInt16(new byte[] { 0x00, 0x43 }, 0)
};
var result = shorts.SelectMany(s => BitConverter.GetBytes(s).Reverse()).ToArray();
// SHIFT-JIS
Console.WriteLine($"OUTPUT: {Encoding.GetEncoding("shift-jis").GetString(result)}");
Console.ReadKey();
}
}
}