我有一个EBCDIC格式的文件,需要将其转换为Unicode格式,因为它包含一些外语字符。
发布于 2021-04-12 18:02:51
您需要做的第一件事是弄清楚使用哪个代码页对EBCDIC文件进行编码。美国的EBCDIC代码页是1137,但是因为您说文件中有外国字符,所以很可能不会使用外国字符。
在本例中,我使用了代码页1142,这是北欧EBCDIC代码页。我已经将一些EBCDIC字符放入一个字节数组中。然后,我在每个0x09字节处将字节数组拆分为几行,并将每一行转换为一个C#字符串。C#字符串是unicode,因此您应该能够很容易地将它们写入新文件。
我希望你能以此为起点。
static void Main(string[] args)
{
byte[] inputFile = new byte[] { 0x81, 0x82, 0x83, 0x09, 0xc0, 0x6a, 0xd0 };
IEnumerable<byte[]> ebcdicLines = SplitBytes(inputFile);
Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(1142); // Codepage 1142 is nordic EBCDIC
IEnumerable<string> lines = ebcdicLines.Select(l => encoding.GetString(l)); // Convert each line to string (unicode)
foreach (var line in lines)
{
Console.WriteLine(line);
}
}
static IEnumerable<byte[]> SplitBytes(byte[] bytes)
{
int currentIndex = 0;
int newlineIndex = Array.IndexOf(bytes, (byte)0x09, currentIndex);
while (newlineIndex > -1)
{
yield return bytes.Skip(currentIndex).Take(newlineIndex - currentIndex).ToArray();
currentIndex = newlineIndex + 1;
newlineIndex = Array.IndexOf(bytes, (byte)0x09, currentIndex);
}
yield return bytes.Skip(currentIndex).ToArray();
}https://stackoverflow.com/questions/67055627
复制相似问题