gpt4 book ai didi

c# - EBCDIC 到 ASCII 的转换,处理数值

转载 作者:行者123 更新时间:2023-11-30 16:20:26 25 4
gpt4 key购买 nike

我正在尝试将文件从 ECDIC 格式转换为 ASCII 格式,但遇到了一个有趣的问题。这些文件包含固定长度的记录,其中一些字段是带符号的二进制整数(在记录布局中描述为 B4)和长精度数字值(在记录中描述为 L8布局)。我已经能够毫无问题地转换字符数据,但我不确定如何转换这些数值。来自原始系统的引用手册(IBM 5110),字段描述如下。

B indicates the length (2, 4, or 8 bytes) of numeric data items in fixed-point signed binary integer format that are to be converted to BASIC internal data format. For record I/O file input, the next 2, 4, or 8 bytes in the record contain a signed binary value to be converted by the system into internal data format and assigned to the variable(s) specified in the READ FILE or REREAD FILE statement using a FORM statement.

L indicates long-precision (8 characters) for numeric values. For input, this entry indicates that an eight-position, long-precision value in the record is to be assigned without conversion to a corresponding numeric variable specified in the READ FILE or REREAD FILE statement.

编辑:这是我用于转换的代码

private void ConvertFile(EbcdicFile file)
{
if (file == null) return;

var filePath = Path.Combine(file.Path, file.FileName);
if (!File.Exists(filePath))
{
this.Logger.Info(string.Format("Cannot convert file {0}. It does not exist.", filePath));
return;
}

var ebcdic = Encoding.GetEncoding(37);
string convertedFilepath = Path.Combine(file.Path, file.ConvertedFileName);
byte[] fileData = File.ReadAllBytes(filePath);

if (!file.HasNumericFields)
File.WriteAllBytes(convertedFilepath, Encoding.Convert(ebcdic, Encoding.ASCII, fileData));
else
{
var convertedFileData = new List<byte>();
for (int position = 0; position < fileData.Length; position += file.RecordLength)
{
var segment = new ArraySegment<byte>(fileData, position, file.RecordLength);
file.Fields.ForEach(field =>
{
var fieldSegment = segment.Array.Skip(segment.Offset + field.Start - 1).Take(field.Length);
if (field.Type.Equals("string", StringComparison.OrdinalIgnoreCase))
{
convertedFileData.AddRange(
Encoding.Convert(ebcdic, Encoding.ASCII, fieldSegment.ToArray())
);
}
else if (field.Type.Equals("B4", StringComparison.OrdinalIgnoreCase))
{
// Not sure how to convert this field
}
else if (field.Type.Equals("L8", StringComparison.OrdinalIgnoreCase))
{
// Not sure how to convert this field
}
});
}

File.WriteAllBytes(convertedFilepath, convertedFileData.ToArray());
}
}

最佳答案

您必须首先知道固定记录大小。使用 FileStream.Read() 读取一条记录的字节数。然后 Encoding.GetString() 将其转换为字符串。

然后使用 String.SubString() 从记录中提取字段。 B4 只是一个长度为 4 的 SubString 调用,L8 长度为 8。进一步使用 Decimal.Parse() 将此类字段转换为数字。您可能需要对结果进行除法,不清楚使用的是什么定点乘法器。 100 的好机会。

关于c# - EBCDIC 到 ASCII 的转换,处理数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14229925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com